question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
4,810,142
4,810,165
Are C++ iterators "safe"?
I have read the documentation for C++ list iterators, but couldn't figure out one thing: are C++ iterators "safe"? I mean, does it stop incrementing once it reaches the last existing element in a list? []'s
No, they're not "safe" in that sense. It is possible to increment an iterator past the end. For all the iterators in the standard library doing this will result in undefined behaviour. You could define your own iterators that do behave in a safe way instead if you wanted to.
4,810,272
4,810,319
C++ Inherited template classes don't have access to the base class
I am working with template classes for the first time, and trying to figure out why the compiler doesn't seem to like when I use inheritence. Here is the code: template <typename T> struct xPoint2 { T x; T y; xPoint2() { x = 0; y = 0; }; }; template <typename T> struct xVector2 : xPoint2<T> { xVector2...
You need to help the compiler out by using this->x and this->y. http://www.parashift.com/c++-faq/templates.html#faq-35.19
4,810,340
4,810,358
3d -> 1D array indexing
in C++, what is the indexing value for a W * H * D sized 3D array? for a particular i, j, k is this the correct indexing: i*W*H+j*W+k
What you have written is equivalent to the pointer arithmetic that this would do: T x[D][H][W]; x[i][j][k]; // Pointer arithmetic done here Obviously, depending on how you order D, H and W (or i, j, k), the calculation will differ.
4,810,721
4,813,882
Methods for encrypting an archive in C++
I'm writing a game that will have a lot of information (configuration, some content, etc) inside of some xml documents, as well as resource files. This will make it easier for myself and others to edit the program without having to edit the actual C++ files, and without having to recompile. However, as the program is s...
I think you misunderstands the possibilities brought up by encryption. As long as the program is executed on an untrusted host, it's impossible to guarantee anything. At most, you can make it difficult (encryption, code obfuscation), or extremely difficult (self-modifying code, debug/hooks detection), for someone to re...
4,810,911
4,811,070
Can someone explain this?
what do you mean by following line ? void(*fnctn)(void(*)(int *,void **),int(*)(void**,int*));
What you have essentially is a function pointer 'fnctn' which takes two function pointers for its two parameters. If we break this down bit by bit, what you have is the following: The first parameter void(*)(int*, void**) is a function pointer returning void and taking an int* and void** as it's two parameters. The sec...
4,810,994
6,820,079
Configuring Visual Studio to create 32-bit and 64-bit configurations
I'm currently trying to configure Visual Studio to automatically set up the appropriate configurations for 32-bit and 64-bit compilation. Ideally, I'd like to be able to have Visual Studio automatically show x64 as a platform under the Configuration Manager. How can I configure VS so any new project I create has this? ...
Visual Studio 2010 and 2008 both provide a way to do this. Project Templates are used by VS to create new projects. These templates can be copied and updated as alternate versions or the originals can even modified in place. You can either use the VS editor to modify the Project Template or you can do it manually; it's...
4,811,351
4,811,410
why this code dont work? why do i need the return type to be a reference?
ostream operator<<(ostream& os, class n); i need to know whats happening inside and why it doesnt work if the return type is not a reference. And i need some links to good articles about istreams and ostreams that help me understand them (not too complicated articles please :D:D) thank you very much. UPDATE 1: plea...
std::ostream's copy constructor is private - which means you cannot create a copy of a stream object. Each stream has an associated underlying buffer - which handles the reads/writes (for example filebuf manages the reads/writes to files). If you were to make a copy of the stream, what do you propose to do with this u...
4,811,374
4,971,414
Can Xcode recognize class variables in C++
For example, this simple class: class Test { public: Test(); int _public; }; Test::Test() { this->_public = 0; // Shows _public in color _public = 5; // Stay White } This seem to work for Cocoa apps, but not on C++. Just to be a bit clearer from my original post, this DOES compile and run exactly as e...
You are right, in Xcode 3 it doesn't work. Xcode 4 however does fix this, as it uses a much deeper integration of the compiler. It's not out yet (if you have a developer account you can download a preview), but it will probably be released soon, patience ;)
4,811,427
4,811,472
Absolute fastest way to store a 32-bit integer to disk?
I have a very latency sensitive routine that generates integers sequentially, but needs to store the last generated one to disk in case of a crash or re-start. Currently I'm doing a seek to beginning of file then writing out the integer then flush each time a new int is generated. The flush is required so the write ...
I would think the fastest/easiest way to do this would be with mmap/msync -- mmap 1 page of the file into memory and store the value on that page. Any time the value changes, call msync(2) to force the page back to disk. This way you need only one system call per store
4,811,574
4,811,587
C++, object declaration in header files
I have some class, and in it I want to create object of another class ... Usually I do it in header file, I just put something like: QString RSSName; and it works because that class has constructor that has no parameters ... So here's my problem: how do I do that for some class(let's say ErrorOutput) that has only con...
It's a bit hard to tell from your description what exactly you are asking for, but it sounds like "RSSName" is a member variable in your class. If I'm correct about that, initialize it in the constructor's initialization list. class Foo { public: Foo() : RSSName(someVal) { } private: QString RSSName; }
4,811,579
4,811,602
is *(1 + &foo) the same as *(&foo + 1) in C/C++?
Is this: *(1 + &foo) the same as this? *(&foo + 1) '+' and '&' have the same precedence and they are evaluated right-to-left. However you can't interpret the second case like this: *(&(foo + 1)) ...because you can only use '&' with an l-value (it won't even compile if you write it like that). So will it be garbage? ...
Yes, they are equivalent (the third one obviously is not). The unary & operator has higher precedence than the binary + operator (as all unary operators do), so &foo + 1 parses as (&foo) + 1. What you are thinking of when you say they have the same precedence is the unary + operator (which is a different operator) has ...
4,811,596
4,811,652
using namespace in function implementation
In C++, could I use using namespace std; declaration in the function implementation files?
By "function implementation files" do you mean the .h files or the .cpp files? (I would normally call .cpp files "implementation" files, while .h files are "interface" files.) If you mean, .cpp files, then of course. That is where you normally see using namespace std. It means that all the code in this .cpp file has ac...
4,811,722
4,813,284
What is the difference between float2 and cuComplex, which to use?
I am trying to figure out how to use complex numbers in both my host and device code. I came across cuComplex (but can't find any documentation!) and float2 which at least gets a mention in the CUDA programming guide. What should I use? In the header file for cuComplex, it looks like the functions are declared with __h...
cuComplex is defined in /usr/local/cuda/include/cuComplex.h (modulo your install dir). The relevant snippets: typedef float2 cuFloatComplex; typedef cuFloatComplex cuComplex; typedef double2 cuDoubleComplex; There are also handy functions in there for working with complex numbers -- multiplying them, building them, et...
4,811,873
4,812,783
QtMultimedia, how can i save Recording in any format like mp3, wav or smth else?
Well, smth like this i was saw in tutorial, but i wanted to save in one of the readable formats for music player. Is it possible? file = new QFile("smth.raw"); file->open(QIODevice::WriteOnly | QIODevice::Truncate ); QAudioFormat format; format.setFrequency(8000); format.setChannels(1); format.setSampleSize(8); form...
Well, if it interesting for somebody, that's algorithm to convert. If you have the better idea, please, reply! #include <stdio.h> int rawToWav(const char *rawfn, const char *wavfn, long frequency) { long chunksize=0x10; struct { unsigned short wFormatTag; unsigned short wChannels; ...
4,812,256
4,812,337
Problems with STL as a static volatile member
I'm trying to compile something like this: #include <list> class thread { public: static volatile std::list<thread *> threadList; //This is also protected by a mutex }; volatile std::list<thread *> thread::threadList; void main() { thread A; thread::threadList.push_back(&A); thread::threadList.remove(&A); } I...
Remove volatile and remove the problem. So for the real answer, it might help if you explain why you need to volatile, and what it is intended to mean here. It won't make the whole list be treated as volatile. See also previous answer
4,812,340
4,813,155
Does xlc in AIX 5 support c++ abi?
Does xlc in AIX 5 support c++ abi?
In between versions of xlc, the C++ ABI is fairly stable. Mixing C++ objects compiled between GCC and xlc may have undefined results.
4,812,445
4,813,342
Why doesn't GCC force parameters in __attribute__((pure)) functions to be const?
The following code compiles without warnings under GCC 4.2, and as far as I can tell, it really shouldn't: #include <fstream> __attribute__((pure)) double UnpureFunction(double* x) { x[0] = 42; return 43; } int main () { double x[] = {0}; double y = UnpureFunction(x); printf("%.2f %.2f\n", x[0], y); } (It ...
As far as I know, pure is your promise to the compiler, but it won't try and verify that you're not lying. Even if it did force parameters to be const, those parameters could be lying (e.g. an object might have a mutable member that's modified when your code calls a member function). If you're looking for const correct...
4,812,491
4,812,522
How to deal with SIGINT?
When I catch SIGINT signal in my program, how can I safely clean up resources? In signal handler function it is impossible to call delete operator, because I don't know how to release resource created with new operator. Any ideas?
If your application is shutting down, don't worry about memory. The OS is going to throw it all away once you terminate anyway. The things you need to clean up in your signal handler is stuff that's going to outlive your process otherwise - for example, if a child process you've created needs to exit also, you should t...
4,812,618
4,812,652
Typecasting from struct to LPVOID
Worked fine before I threw it into a class. Any help for resolving this typecasting error? Error error C2440: 'type cast' : cannot convert from 'IAT CInjector::* ' to 'LPVOID' Code Referenced WriteProcessMemory(CInjector::_hProc, CInjector::_iatBaseAddress, (LPVOID) & CInjector::_iat, // typecasting error? ...
The problem is that &CInjector::_iat is a pointer-to-class-member, not a real pointer. Since _iat isn't static, each class has its own copy of it, and so &CInjector::_iat is not an address, but rather is typically an offset into a class. You can use it with the "pointer-to-member-selection" operator .*: CInjector myC...
4,812,837
4,812,889
c++ library to make tar files
Is there any c++ library available which can create tar files ? I have stream of text which I need to break into parts and make small files which should all reside in a tar ball ! Regards, Lalith
A quick Google search uncovers the Chilkat C/C++ TAR Library. A sample of its use is available here: Chilkat C++ Examples: Create TAR Archive Another possible option is libtar (note, however, that it is a C library). And, of course, you could read the TAR file spec (all of what you need is linked through Wikipedia) and...
4,812,891
4,812,963
fork() and pipes() in c
What is fork and what is pipe? Any scenarios explaining why their use is necessary will be appreciated. What are the differences between fork and pipe in C? Can we use them in C++? I need to know this is because I want to implement a program in C++ which can access live video input, convert its format and write it to ...
A pipe is a mechanism for interprocess communication. Data written to the pipe by one process can be read by another process. The primitive for creating a pipe is the pipe function. This creates both the reading and writing ends of the pipe. It is not very useful for a single process to use a pipe to talk to itself. In...
4,813,097
4,813,978
What C++ code compiles down to the x86 REP instruction?
I'm copying elements from one array to another in C++. I found the rep movs instruction in x86 that seems to copy an array at ESI to an array at EDI of size ECX. However, neither the for nor while loops I tried compiled to a rep movs instruction in VS 2008 (on an Intel Xeon x64 processor). How can I write code that wil...
If you need exactly that instruction - use built-in assembler and write that instruction manually. You can't rely on the compiler to produce any specific machine code - even if it emits it in one compilation it can decide to emit some other equivalent during next compilation.
4,813,234
4,813,245
How to create an installer for windows service built in C++
I want to create an installer for windows service built in C++. I have followed this article to create the Service. I have 3 win32 console application in my solution. one for installation , one for uninstallation and one that does the actual work.
I must humbly recommend WiX (Windows Installer XML Toolset) for all your installer needs.
4,813,292
4,813,316
RGBApixel memory issue with EasyBMP c++
I have the following line in my main() function (which uses EasyBMP): RGBApixel * myPixel = myFavoriteColor(192); which is defined as: RGBApixel * myFavoriteColor(int intensity) { RGBApixel color; color.Red = 0; color.Green = intensity/2; color.Blue = intensity; return &color; } and I'm getting the following error...
You are returning the address of the local variable color which will not be valid after exiting the function myFavoriteColor. The object color will be destroyed at the end of the function. Instead return a copy the object RGBAPixel by chnaging the function signature to RGBAPixel myFavoriteColor(int) and using return co...
4,813,516
4,813,545
C++ Multithreading - When does a child thread exit?
I create a thread to whom a void* to a structure is passed as argument. This structure is created in a class. When this class destructor is called, that is at the end of main, the structure is deleted. So later i see the child thread is launched again, and referring to its void* argument throws an exception as its alre...
One option would be to have the main thread signal the child thread that it should exit (perhaps by setting a Boolean flag), then using WaitForSingleObject at the end of main() to wait for the thread to terminate before returning and calling the destructors. This prevents the error you've described by forcing the thre...
4,813,806
4,813,823
Problem deserializing data with protobuf-net that was serialzed by google's protobuf
I am currently working on code that serializes in one app (C++) and needs to deserialize it in another (C#). I am trying to use google proto + protobuf-net but something is failing. Both the .cc and the .cs message definition files were generated with their respective compilers, from the same .proto file. The data is ...
Rewind your stream - it is at the end, so Read will return no data: memStream.Write(buffer, 0, recv); memStream.Position = 0; // <===========here ProtoData data = ProtoBuf.Serializer.Deserialize<ProtoData>(memStream); alternatively, use the overloaded constructor to prepare the stream: using (MemoryStream memStream = ...
4,813,947
4,814,564
How can I know which parts in the code are never used?
I have legacy C++ code that I'm supposed to remove unused code from. The problem is that the code base is large. How can I find out which code is never called/never used?
There are two varieties of unused code: the local one, that is, in some functions some paths or variables are unused (or used but in no meaningful way, like written but never read) the global one: functions that are never called, global objects that are never accessed For the first kind, a good compiler can help: -W...
4,814,074
4,814,697
Qt Plugin with OpenMP Support on MinGW: Undefined reference?
I am developing a "Qt Plugin" which uses OpenMP (OpenMP support can be enabled/disabled using CMake parameter). I use MinGW and CMake as development environment. This is how I enable/disable OpenMP in the code: #ifdef OPENMP_ENABLE #pragma omp parallel for #endif for(int i=0; i<volumeData->getZSize(); i++){ . I hav...
OpenMP requires a runtime library (called libgomp in case of gcc), which must be linked into the created executable. It is therefore not sufficient to add the OpenMP flags to the compilation flags, they must also be added to the link flags: set_target_properties(<target_name> LINK_FLAGS "${OpenMP_CXX_FLAGS}") Of cour...
4,814,290
4,814,349
from member of nested list, how can I call outside data
struct object { string sent ; ...// other data declaration struct nested { void read ( void ) ; }; }; In read function, how Can I fill sent ?In other words, how can I call sent EDIT : I know this is a trivial question, but I donot know so much about nested structure, and can you gi...
The nested class simply needs a pointer or reference to the enclosing class. This can be passed in via the nested class's constructor. struct nested { nested(object& obj) : m_obj(obj) { } object& m_obj; }; You can then access object::sent through the m_obj reference variable.
4,814,487
4,814,595
Efficient algorithm for merging small overlaping blocks into larger contiguous blocks?
i am faced with a rather interesting problem. I have a (fairly large) number of blocks. A block is simply something starting at an offset and having a length and a color. The offset and length are limited - the space where these blocks exist is <0-N> where N ranges from hundreds of thousands to a few million. An invali...
I would suggest the following: Create a separate list for each of the colors For each specific color, calculate the beginning (offset) and the end (offset + length) of all blocks Sort each color-specific list by value of beginning Now, traverse each of the lists, merging the items: if the next item's beginning is less...
4,814,649
4,814,806
protection from erronous input
I worked with numbers ( int, float, double, long, unsigned ), but when I put other character to console ( such as ^[[A, or * ). Therefore, my program is crashing How can I protect my program from this erroneous input ? Note : I know some library function namely isdigit or isallnum, but they don't help so much
In C++ it's possible to do this by filtering the data through a stringstream. There's a discussion of how to do this at Stanford's introductory C++ course site, with full code for reading integers on page 19. The rest of the chapter is also a good resource in general for how to do I/O in C++, which might also be usef...
4,814,668
4,814,901
Addition of two chars produces int
I've made a simple program and compiled it with GCC 4.4/4.5 as follows: int main () { char u = 10; char x = 'x'; char i = u + x; return 0; } g++ -c -Wconversion a.cpp And I've got the following: a.cpp: In function ‘int main()’: a.cpp:5:16: warning: conversion to ‘char’ from ‘int’ may alter its value The same...
What you're seeing is the result of the so-called "usual arithmetic conversions" that occur during arithmetic expressions, particularly those that are binary in nature (take two arguments). This is described in §5/9: Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yie...
4,814,930
4,818,398
Get line/column of an XPath query in Pugixml
We want to get the line/column of an xpath query result in pugixml : pugi::xpath_query query_child(query_str); std::string value = Convert::toString(query_child.evaluate_string(root_node)); We can retrieve the offset, but not the line/column : unsigned int = query_child.result().offset; If we re-parse the file we can...
result().offset is the last parsed offset in the query string; it will be equal to 0 if the query got parsed successfully; so this is not the offset in XML file. For XPath queries that return strings the concept of 'offset in XML file' is not defined - i.e. what would you expect for concat("a", "b") query? For XPath q...
4,814,952
4,814,982
Is c++ a space free language?
#define PR ( A, B ) cout << ( A ) << ( B ) << endl ; - error -> A was not declared in scope - error -> B was not declared in scope - error -> expected "," before "cout" I thought C++ was space free language but when I write above code, then I see some errors. I am still thinking "Is my console is not working...
There are numerous exceptions where whitespace matters; this is one of them. With the space after PR, how is the preprocessor supposed to know whether (A,B) is part of the macro expansion, or its arguments? It doesn't, and simply assumes that wherever it sees PR, it should substitute ( A, B ) cout << ( A ) << ( B ) ...
4,815,018
4,815,061
Is it possible to access the underlying pointer from a given iterator to a vector?
I have a vector defined as vector<char>, and I have some function which gets called at some point that receives a range - something like the following: template <typename Iterator> void foo(Iterator& start, Iterator& end) { } In the above function, I currently have a call to std::find to look for a given character - t...
If you know that you have a std::vector<T>::iterator, then it is safe to do &*it. Note, however, that it is not safe to convert this to unsigned long long *, as the alignment requirements will be different.
4,815,155
4,815,278
producing c code from c++
Possible Duplicate: Code convert from C++ to C Two months ago, my instructor have asked one question, I have searched to looking for answer but I could not find it. question : From c++ code, how can one generate c code just using console ( with g++ ) . How can I do this ?
g++ compiles C++ directly to machine code, it does not first compile to C then compile that. There may be some compilers that compile to C code first. I do not know of any if you really need the code. It is not the most efficient way to do it though. I think that is what your instructor was trying to ask you, i.e. if t...
4,815,177
5,265,005
Garbage from other linking units
I asked myself the following question, when I was discussing this topic . Are there cases when some unused code from translation units will link to final executable code (in release mode of course) for popular compilers like GCC and VC++? For example suppose we have 2 compilation units: //A.hpp //Here are declarations...
As other posters have indicated, the linker typically does not remove dead code before building the final executable. However, there are often Optimization settings you can use to force the linker to try extra hard to do this. For GCC, this is accomplished in two stages: First compile the data but tell the compiler to...
4,815,423
4,816,216
How do I set the working directory to the "solution directory"?
I want to set the current directory to the solution directory/configuration name. How do I do that? Can I use the global variables somehow? I am trying to read a file and the current directory changes in the middle of the code. I want to change it back.
If your current directory is changing, you should probably save your working directory at startup in some variable you can access later to set cwd back there. At least this is how I understand your question. For getting the cwd, this might help.
4,815,433
4,815,832
Error using hashlib++ in c++ builder?
I downloaded the latest hashlib++ 0.32 version and tried to use hash functions but it says Unsupported compiler. [BCC32 Fatal Error] hl_types.h(71): F1003 Error directive: "Unsuppported compiler." "Please use GCC,MINGW,MSVC " " or define hl_uint64 for your compiler in hl_types.h line 62" The ...
I think the error message pretty much says what to do... add the following to the header file below the _MSC_VER check and above the final #else: #elif defined( __BORLANDC__ ) typedef unsigned __int64 hl_uint64; (Builder has an "__int64" extended integer type)
4,815,452
4,815,541
more problem with nested structure
object *head = NULL, *tail = NULL; // EDIT struct object { vector <int> data; object * read ( void ) ; struct obj { obj *next; object * brach ( object * ) ; }; }; object * object :: read ( void ) { ... // some code to read and return ...
Seems you are from a non-C++ background (C#?). In response to some of your queries: Correct way to address a global from your scope of object::read() is either simply Show(Head) or ::Show(head) - I suspect the reason you are having problems here is because head is not defined. In you main procedure you need to use the ...
4,815,679
4,816,237
Run QDialog object from a static function after QMainWindow is opened
I would like to open a modal dialog box (to log in) from a static function after the QMainWindow object is opened. class DialogLog : public QDialog { DialogLog(QWidget * parent) : QDialog(parent) { //some code exec(); } }; class LogHandler { static bool log(QWidget * parent) { Dialo...
There could be a better solution, but here is what you could do : use a singleshot timer that will shot immediatly (i.e. as soon as the event pump will be looping). The timer will call a slot of, for instance, your WinMain class : void main(..) { QApplication app(..); WinMain fen; fen.show; QTimer::si...
4,815,689
4,815,754
Is it safe to bind a reference to a not yet constructed object in C++?
Consider this code sample: class Base { public: Base( string& _object ) : object( _object ) {} private: string& object; }; class Derived: public Base { public: Derived() : Base( object ) {} private: string object; }; Obviously first Base is constructed and it is passed a reference to a not yet construc...
It is safe, as long as you don't "use" the reference before object is constructed. You can use the base-from-member idiom to move object into a (private) base class which comes before Base, and thus be constructed before Base, if you need to change the construction order: struct Base { Base(string &ref) { cout <...
4,815,819
4,815,851
C++ return value without return statement
When I ran this program: #include <iostream> int sqr(int&); int main() { int a=5; std::cout<<"Square of (5) is: "<< sqr(a) <<std::endl; std::cout<<"After pass, (a) is: "<< a <<std::endl; return 0; } int sqr(int &x) { x= x*x; } I got the following output: Square of (5) is: 2280716 After pass, (a)...
Strictly, this causes undefined behavior. In practice, since sqr has return type int, it will always return something, even if no return statement is present. That something can be any int value. Add a return statement and turn on warnings in your compiler (g++ -Wall, for instance). int sqr(int &x) { return x = x*x...
4,815,934
4,815,998
How to check whether GUID is zero
What is the most concise yet readable way to check whether a GUID is zero? I have come up with the following code: GUID myGuid /* = ... */ ; GUID zeroGuid; memset(&zeroGuid, 0, sizeof(zeroGuid)); if (!IsEqualGUID(myGuid, zeroGuid)) { // ... do something if GUID is not zero ... } But I think above code is too clums...
Compare with GUID_NULL: if( myGuid != GUID_NULL ) { //do stuff }
4,815,956
4,816,030
Base-from-Member Idiom in C++
The following code is from here: #include <streambuf> // for std::streambuf #include <ostream> // for std::ostream class fdoutbuf : public std::streambuf { public: explicit fdoutbuf( int fd ); //... }; class fdostream : public std::ostream { protected: fdoutbuf buf; public: explicit fdostr...
The order of initialization is determined by the order of declaring your class members, and inherited classes come before all of that. Take a simple example that illustrate the basic problem without referring to inheritance : class C { int a, b; public: C() : b(1), a(b) {} // a is initialized before b! }; The code...
4,815,959
4,816,245
C# Converting a XOR crypt function
I've been working on converting a C++ crypting method to C#. The problem is, I cant get it to encrypt/decrypt the way I want it to. The idea is simple, I capture a packet, and decrypt it. The output will be: Packet Size - Command/Action - Null (End) (The decryptor cuts off the first and last 2 bytes) The C++ code is th...
I just tried your function and it seems ok: class Program { // OP's method: http://stackoverflow.com/questions/4815959 public static byte[] CryptPacket(byte[] packet) { int paksize = packet.Length - 2; for (int i = 2; i < paksize; i++) { packet[i] = (byte)(0x61 ^ packet[i...
4,816,156
4,816,419
Are IEEE floats valid key types for std::map and std::set?
Background The requirement for a comparator on the key type of an associative container (for example std::map) is that it imposes a strict weak order on the elements of the key type. For a given comparator comp(x, y) we define equiv(x, y) = !comp(x, y) && !comp(y, x). The requirements for comp(x, y) being a strict weak...
I suspect the restrictions should be taken as referring to the relation's behavior on the values actually used as keys, not necessarily on all values of the type. Don't have time at the moment to go through the standard looking for "smoking gun" language that refers to actual container elements rather than all values o...
4,816,164
4,816,222
error: assignment of read-only location <unnamed>::g_namesmap
I am encountering the error mentioned in the title of this question. The code snippet looks like this: namespace { struct myOptVar * g_optvar = 0; //Variable that stores map of names to index std::map<std::string, const size_t> g_namesmap; }; void Optimizations::generate() { // free current optvar str...
Because your map data_type is declared with the const qualifier: std::map<std::string, const size_t> g_namesmap; When you use the [] operator with an std::map, it returns a reference to the data_type object associated with the specified key_type value. In this case, your data_type is const size_t, so of course you ca...
4,816,545
4,817,078
Boost POOL usage - singleton
I have started using boost pools as singleton defined in boost/pool/singleton_pool.hpp as I need to allocate a lot of structures of same size repeatedly. The performance improvement is phenomenal as I was using malloc before. The objects that I allocate are put in a list by a producer thread and a consumer thread takes...
According to the doc : bool t.release_memory() t must be ordered. Frees every memory block that doesn't have any allocated chunks. Returns true if at least one memory block was freed. bool t.purge_memory() Frees every memory block. This function invalidates any pointers previously returned by allocation func...
4,816,592
4,816,710
wctomb chokes on per mille symbol (‰)
I am trying to print out a bunch of unit labels; some of them contain Greek characters, some have other funny code points. I traced it back to the wctomb functions not knowing what to do with e.g. UTF-16 character 8240: char mb[10]; assert( 0 <= wctomb(mb,8240) ); How can I set the locale used by wctomb to e.g. "All ...
Setting a correct UTF-8 locale will fix it; #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> int main() { setlocale(LC_ALL, "en_US.UTF-8"); char mb[10]; assert( 0 <= wctomb(mb,8240) ); printf("%s\n", mb); return 0; } See http://ideone.com/sflZj
4,816,698
4,816,751
Avoiding Circular Dependencies of header files
Do you have any good advice on how to avoid circular dependencies of header files, please? Of course, from the beginning, I try to design the project as transparent as possible. However, as more and more features and classes are added, and the project gets less transparent, circular dependencies start happening. Are th...
If you have circular dependency then you doing something wrong. As for example: foo.h ----- class foo { public: bar b; }; bar.h ----- class bar { public: foo f; }; Is illegal you probably want: foo.h ----- class bar; // forward declaration class foo { ... bar *b; ... }; bar.h ----- class foo; // forwa...
4,817,059
4,817,183
C++: static initialize an array member, member at a time
I now I can do this in global scope and everything works fine: const char* Foo::bars[3] = {"a", "b", "c"}; But I want to do this because this is much more clearer and self documenting (especially if you use Enums as the index): const char* Foo::bars[3]; bars[0] = "a"; bars[1] = "b"; bars[2] = "c"; Is it anyway possib...
In C++ there is no equivalent of the static Java block. If you really want to initialize the array automatically, you can create a simple class to do the job: // in .cpp class FooInitializer { public: FooInitializer() { Foo:bars[0] = "a"; Foo:bars[1] = "b"; Foo:bars[2] = "c"; } }; stati...
4,817,453
4,821,727
How to prevent console output after exiting the program
I'm writing simple command-line program in C++ (windows). One functionality of it is to check keyboard input and if a certain key is pressed, exit the program. Actually it works fine so far, however when the program exits, I get all the pressed key on the output of the command-line? Is there a way to avoid this behavio...
Use _kbhit() to test if a key is pressed. and when it is use _getch() to get the value. (note _getch() can return 0 or 0xE0 for special keys and call _getch() again for that value)
4,817,526
4,817,648
c++ std::map index variable
Ive got a std::map setup like this: static map<string, string> games; Inside a for loop im trying to assign the variable to the index value like so games[name] = "Yes!"; but that just gives me the error 136: error: no match for operator[] in games[name]
There are two possible causes for that error: The games variable is not an std::map instance. The name variable is not an std::string instance. Also, check if there are no name collisions.
4,817,713
4,829,125
limit access to unc server to the program
I am connecting to an unc server (\blablub\share) from my program (written in c++). Right now i am using WNetUseConnection Function to connect to the server. Now i want to limit the access only to the program. Because right now it is possible to access the unc server using the explorer after the connection has been est...
Use WNetAddConnection3 and leave NETRESOURCE::lpLocalName 0. This does the heavy work of WNetUseConnection but doesn't add a drive letter. Therefore, you'll still need to use \\Server\Share\File names in your program. Don't forget to WNetCancelConnection2 when your program exits. Of course, while your program runs, the...
4,817,808
4,898,922
Problem compiling and using Qt with a non-default compiler
I'm trying to compile and use Qt. For some reason I have to use g++ version 3.4.3 for my application, and not the compiler installed on the system: g++ 4.1.2. I compiled Qt with the environment variables CXX and CC set to the old g++, but still when I link my app with the old g++ I get the following errors: .../qt-4.7....
It turns out that modifying LINK wasn't enough, but when I changed the PATH to point to the old compiler, Qt was compiled and linked solely with the old compiler, and then I was able to link it with my program. Should have thought of that ...
4,818,039
4,818,238
Multi-threaded performance std::string
We are running some code on a project that uses OpenMP and I've run into something strange. I've included parts of some play code that demonstrates what I see. The tests compare calling a function with a const char* argument with a std::string argument in a multi-threaded loop. The functions essentially do nothing and ...
My question is basically whether this is solely due the dynamic allocation of std::string and why in this case that can't be optimized away since it is const and can't change? Yes, it is due to the allocation and copying for std::string on every iteration. A sufficiently smart compiler could potentially optimize this...
4,818,183
4,823,623
Multilevel usage of thread impersonation
I'm having some issues with some long-ago written classes that do thread-level impersonation and process spawning. The problem seems to be that my usage of these utility classes is above and beyond what anyone else has tried to do with them. The first does thread-level impersonation by using OpenThreadToken and Duplica...
OpenThreadToken fails in the impersonated case because the impersonated user does not have permission to access the thread's token. You should pass OpenAsSelf = TRUE.
4,818,424
4,818,496
Vector values not in inserting order
I'm inserting values into a vector: vector<map<vector<string> , vector<string> > > listedParameterMap; like this: listedParameterMap.insert(listedParameterMap.end(), 1, parameterMap); If I check later the vector, the order is inverted. Did I miss something? EDIT: I think it may be somewhere else... I just got an idea. ...
Why don't you simply write: listedParameterMap.push_back(parameterMap); It's simpler interface than what you're doing in your post.
4,818,570
4,818,936
How to find CFBundleRef from a function address or a class
Is it possible to get the Bundle reference (CFBundleRef) from a function address or a class name in Carbon..?? I know there are functions in Objective-C NSBundle myBundle = [NSBundle bundleForClass:(Class)<SOME_CLASS>]; and with Windows API GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)<SOME_FUN...
You can use the Core Foundation functions that operate on CFBundle to get the bundle reference to the bundle that exports a given function name: CFStringRef functionName = CFSTR("someFunctionName"); CFArrayRef allBundles = CFBundleGetAllBundles(); CFIndex i; CFIndex bundleCount = CFArrayGetCount(allBundles); for (i = ...
4,818,573
4,818,803
accuracy of long double sqrt()
I have noticed a problem with the accuracy of the long double version of sqrt(). The following code demonstrates the problem. #include <iostream> #include <cmath> #include <cfloat> int main(int argc, char ** argv) { int count=0; long double s=sqrt(3L); std::cout.precision(21); std::cout << "s=" << s << ", s^2=...
You have two issues here: First, 3L implicitly promotes to double not long double so even though you assign the return value to a long double it's still using the low precision version of sqrt. You'll need to static_cast 3 to long double as the argument. Secondly, only the double version of sqrt is imported into the gl...
4,818,628
4,818,690
C++ figure out if the debugger is attached
I use stackwalk64 to generate stacktraces for C++ in visual studio 2008 using the latest symchk.exe and dbghlp.dll. This works fine when I'm running the standalone exe. However, when the debugger is attached I deadlock visual studio. I previously had a workaround where I downloaded all of the system32 symbols to disk a...
Use IsDebuggerPresent and possibly CheckRemoteDebuggerPresent
4,818,657
4,818,707
What is the proper parameter for glOrtho to make a Top View?
I try to learn OpenGL by creating some sort of 3D Modeler application using Visual C++. The screen will be divied into three window : perspective, front and top (isometric). And I almost give up try to implement the top view. This is my current top view code : glOrtho(-1,1,-1,1,1,3.5f); gluLookAt( 0,2,0,//eye 0,0...
You need to adapt the z far value according to your geometry. You should compute a bounding sphere or bounding box of your model, find the Z range and adapt your camera according to it.
4,818,750
4,818,911
Performance comparison Integer Multidimensional array vs Array of Structures
Are multidimensional arrays better than an array of structures if there's only one datatype? For example would an array of: struct data{ short datapointa; short datapointb; short datapointc; } be better than short data[100][100][100][100]; What if there are several datatypes, would several arrays be bette...
It will depend mainly on your access pattern. You should choose whichever data structure gives you best locality of access - ideally you should be accessing memory contiguously, in order to make best use of cache and minimise memory bus traffic. Obviously this will depend on what kind of algorithm(s) you are using with...
4,818,779
4,819,340
Good source code for compiler components
I am currently taking a course on Compilers. I don't like the idea of blindly memorising facts without any sort of place to apply them to. I want to learn by hands-on doing. So, I would like to have the complete code of 3-4 compilers, possibly for languages with different syntax rules (python,c, c++, java) while worki...
There is a bunch of simple and comprehendable compilers: http://spivey.oriel.ox.ac.uk/corner/Oxford_Oberon-2_compiler http://caml.inria.fr/caml-light/index.en.html http://bellard.org/tcc/ And some tools, not complete compilers, but still useful: http://cil.sourceforge.net/ (a complete C parser and code analysis tool) ...
4,818,785
4,820,180
How to pass parameters to the gtest
How can I pass parameter to my test suites? gtest --number-of-input=5 I have the following main gtest code. And --number-of-input=5 should be passed to InitGoogleTest(). #include <iostream> #include <gtest/gtest.h> int main(int argc, char **argv) { std::cout << "Running main() from gtest_main.cc\n"; ::testing::GT...
Google Test only recognizes its own command-line options. Each time it finds one, it removes it from argv and updates argc accordingly, so after InitGoogleTest returns, anything left over in argv is available for you to process yourself. Use your favorite command-line-parsing technique, store the results in some global...
4,818,850
11,756,773
Is is possible to export functions from a C# DLL like in VS C++?
In VS C/C++ you could use extern "C" __declspec(dllexport) -function declaration-. How do I accomplish this in a C# dll? Is there C# code equivalent to the above code? Edit: More info I am trying to create an add in for Notepad++ and I want to use C#, but the common way I've seen so far is to use legacy C++ code with ...
Unmanaged Exports => https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports DLLExport => https://github.com/3F/DllExport How does it work? Create a new classlibrary or proceed with an existing one. Then add the UnmanagedExports Nuget package. This is pretty much all setup that is required. Now y...
4,819,075
4,819,103
How to output fraction instead of decimal number?
In C++, When I calculate 2/3, it will output decimal values, how can I just get the original format (i.e.g 2/3) instead of 0.66666667 Thanks
You can't. You would need to write a class dedicated to holding rational numbers (i.e. fractions). Or maybe just use the Boost Rational Number library.
4,819,261
4,819,310
generate_n with constructor which takes two arguments
Hi I'm trying to do the following: struct A { A(int i, int j){} } int startValue = 10; vector<A> v; generate_n(back_inserter(v), 10, ???; How can I "deliver" the two arguments startValue and the functor rand? Thank you
Since a generator is a function object, you can instantiate the generator and provide arguments to its constructor: class MyGenerator { private: int startValue; public: MyGenerator(int startValue): startValue(startValue) {} // generate an instance of A A operator()() { return A(startValue, rand(...
4,819,390
4,819,415
can a const function be recursive in C++ , as long as it modies mutable variables?
Can i have a const function that is recursive in my class ?
Yes. const can always call const functions again. You don't even need mutable variables for it to make sense, for example you can pass things by reference into the recursive function and modify those for your state. (Or static variables, or non-members, or other functions which return non-const references or pointers t...
4,819,450
13,990,627
Launch default email client to open a "send email" window with a pre-selected file attachment
I need to add a "Create and email" feauture to our app. Our program creates an output file, and I must then launch the default email client to open a "write email" window, and with the output file preselected as an attachment. I've seen other programs do it, even if the default client is Thunderbird instead of Outlook...
I ended up using MAPI to achieve it. I used LoadLibrary and GetProcAddress to get the needed functions. The code I used is this: bool MailSender::Send(HWND hWndParent, LPCTSTR szSubject) { if (!m_hLib) return false; LPMAPISENDMAIL SendMail; SendMail = (LPMAPISENDMAIL) GetProcAddress(m_hLib, "MAPISe...
4,819,619
4,819,642
Why are there two nested curly braces without any statement in-between?
The code given below is the code generated by MOC in Qt. const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow, qt_meta_data_MainWindow, 0 } }; Why is there two continuous curly braces without anything statement in-between? Also, what does ...
I think it is initializing a list (external braces) of structure (internal braces.)
4,819,724
4,819,773
Fighting Memory Leaks
Memory leaks are a nightmare. I know: I have some. What is the most effective (least painful and time consuming) way to locate them? I use Visual Studio 2010 and develop in C++ for Windows.
Smart Pointers is probably what you are looking for. At least when allocating objects. For containers, use the STL where possible. If you are looking for existing memory leaks, you can use DEBUG_NEW if you are in VS2010.
4,819,876
4,819,926
C++ pointers - What values are held here?
If I have the following pointer variable declarations: int *a; int **c; Regarding to the type and what values each will hold, will it be as follows: a is of type int*, and will hold a memory address *a is of type int, and will hold the value of the variable the pointer is pointing to c is of type int**, and will ho...
int *a; int **c; You are correct about a. It is more common to say a holds a pointer to int. c is of type int** and will hold a pointer to a pointer to int. *c is of type int*, and will hold a pointer to int. **c is of type int, and will hold an integer value. You are correct about c pointing to b and b pointing to ...
4,819,936
4,820,339
Why no default move-assignment/move-constructor?
I'm a simple programmer. My class members variables most often consists of POD-types and STL-containers. Because of this I seldom have to write assignment operators or copy constructors, as these are implemented by default. Add to this, if I use std::move on objects not movable, it utilizes the assignment-operator, me...
The implicit generation of move constructors and assignment operators has been contentious and there have been major revisions in recent drafts of the C++ Standard, so currently available compilers will likely behave differently with respect to implicit generation. For more about the history of the issue, see the 2010 ...
4,820,003
4,820,524
InitOnceExecuteOnce exception safety
I have a exception safety issue on InitOnceExecuteOnce WinAPI function. Whenever exception is thrown from callback function deadlock is occurred. Callback returns boolean flag telling the caller whether the data is successfully initialized, but if I return false I will not be able to rethrow exception, that's not good....
You should not throw C++ exceptions through code that does not expect it, (eg. C code, or in your case, the Windows API). instead, have your callback return false on error, which will be reflected in the return from InitOnceExecuteOnce
4,820,018
4,820,034
#pragma deprecate a function based on signature?
in Visual Studio is it possible to #deprecated a function, based on the signature of the function and not simply the name? In my case we're in C++ and don't want to deprecate all flavors of the function int foo(); <-- we want to keep int foo(int x); <-- we want to deprecate
Just do this: __declspec(deprecated) void foo(int) {} And if you want the compiler to generate a specific message when compiling a deprecated function, then do this: __declspec(deprecated("foo(int) is a deprecated function.")) void foo(int) {}
4,820,087
4,820,115
C++ Inherited template classes & initialization lists
I have been converting some of my math classes to templates and to use initialization lists, and run into a problem when the inherited class needs to access base class data members on initialization. Here is the code: template <typename T> struct xCoord2 { T x; T y; xCoord2(T _x, T _y) : x(_x), y(_y) {}; }...
You need to invoke the base class constructor: xCoord3(T _x, T _y, T _z) : xCoord2(_x, _y), z(_z) { } This would be no different if these were nontemplate classes: you can only initialize the base classes and member variables of the derived class in the derived class constructor.
4,820,240
4,820,268
NSMutableArray insertObject:(id) atIndex:int inserting a void ptr
In my application, i have a mix of C++ and Objective C++ code, at one place, i need to insert pointer of c++ class object to NSMutableArray , but i am getting NSINvalidArgument exception, Can anyone guide me, how can i insert void pointer to NSMuatableArray This is what i have tried , pArray = [[NSMutableArray alloc...
NSArrays expect to hold objective-C objects conforming to the NSObject protocol. If you wish to wrap a pointer, use NSValue: [myArray insertObject:[NSValue valueWithPointer:node] atIndex:idx]; You are manually responsible for all memory management of that pointer, as objective-C can't reference count it in the usual w...
4,820,308
4,820,768
Borland C++ v5.5 installation procedure
I have downloaded the latest version available of Borland C++ 5.5 compiler. I have installed the exe file but the program doesn't run. I have got this in READ ME file of the installation package but I cant make out anything.. Installing and running the Command Line Tools Run freecommandlinetools.exe; choose the ...
Borland 5.5 is an extremely old compiler. It doesn't even implement std::string properly. Use a more modern compiler, like g++ or Visual C++ (they're both free). Cheers & hth.,
4,820,374
4,820,430
SQLite escape string c++
Consider the following code char bar[] = "hello world \"One\", two, 'three'"; char *zSQL = sqlite3_mprintf("INSERT INTO stuff (`foo`) VALUES ('%q');", bar ) ; sqlite3_exec(db, zSQL, 0, 0, 0); sqlite3_free(zSQL); /* Produces a exception error */ The problem is that the quotes are not getting escaped in the SQL statem...
No. Use bound parameters. See: http://www.sqlite.org/c3ref/prepare.html http://www.sqlite.org/c3ref/bind_blob.html
4,820,545
4,820,611
How to get locale on iPhone in C++?
Everything I see about iPhone localization is, unsurprisingly, in Objective-C. The project I'm working on is already written and working on iPhone using almost entirely C++, and we have a few complete translations already. All we need now, is a way to find out the locale/language code. On the computer, this is done usi...
Probably you want to use CFLocaleGetValue()
4,820,643
4,820,851
Understanding std::swap(). What is the purpose of tr1::_Remove_reference?
In the STL implementation of VS10 there is the following code for a variant of std::swap(): // TEMPLATE FUNCTION _Move template<class _Ty> inline typename tr1::_Remove_reference<_Ty>::_Type&& _Move(_Ty&& _Arg) { // forward _Arg as movable return ((typename tr1::_Remove_reference<_Ty>::_Type&&)...
_Remove_reference is a template that, well, removes the reference from its type. I'm pretty sure that the template is specialized for T& and T&& with the same typedef, right? Not sure how much I should go into details here. Are you familiar with template metaprogramming? _Move seems to do exactly what std::move does: i...
4,820,659
4,821,278
Maintaining Floating Point Accuracy with a Running Average
I need to calculate the mean-squared error of a 16-bit operation for an arbitrary number of data points (upwards of 100 million). I decided to go with a running average so I wouldn't have to worry about overflow from adding a large number of squared errors. At 100 million samples I had problems with floating point pr...
Floating point numbers don't overflow in this kind of situation, they only lose precision. So there are no advantages of a running average over a running total here. The consequence is the same whether the running total or the denominator grows. To maintain precision in a running total, keep subtotals instead of a sing...
4,820,843
4,820,975
How to typedef the iterator of a nested container?
What is the proper way to declare the iterator i in the following code? #include <iostream> #include <vector> using namespace std; template<class Mat> void f(const Mat& mat) { typedef typename Mat::value_type::iterator itr; //itr i = (mat.begin())->begin(); //This Line Gives an error typeof((mat.begin(...
Do it the STL way and pass iterators, not containers: //Beware, brain-compiled code ahead! template<typename It> void f(It begin, It end) { typedef typename std::iterator_traits<It>::value_type cont; typedef typename cont::const_iterator const_iterator; // note the const_ pfx const_iterator i = begin->be...
4,820,992
4,821,232
Complex loop in a C++ program portable to OpenMP and MPI?
I have a C++ number crunching program. The structure is: a) data input, data preparation b) "big" loop, uses global and local data (lots of different variables in both cases) c) postprocess results and write data The most intensive part is "b", which is basically a loop. I need to speedup the program in a cluster. 25 b...
Actually, you should use both. Use MPI to distribute tasks between blades and OpenMP to fully utilize each blade. Take some time to understand how memory and sharing works on each case.
4,820,998
4,821,069
Resizing an "std::vector"; which elements are affected?
std::vector<AClass> vect; AClass Object0, Object1, Object2, Object3, Object4; vect.push_back(Object0); // 0th vect.push_back(Object1); // 1st vect.push_back(Object2); // 2nd vect.push_back(Object3); // 3rd vect.push_back(Object4); // 4th Question 1 (Shrinking): Is it guarantied that the 0th, 1st and 2nd...
Question 1: Yes, the standard says: void resize(size_type sz); If sz < size(), equivalent to erase(begin() + sz, end());. Question 2: If no resizing is required, yes. Otherwise, your elements will be copied to a different place in memory. Their values will remain unchanged, but those values will be stored somewhere ...
4,821,268
4,821,676
Friendship vs inheritance
I've the class hierarchy below. Basically, I would like to establish a "has-a" relationship between the classes Foo and CComplexMat, i.e. class Foo "has-a" CComplexMat. From what I know, private and protected members of a class cannot be accessed from outside the class where they are defined. However, there are two pos...
Inheritance should only be used for "is-a" relationships. It looks to me like CComplexMat<T> has two CMatrix<T> members, but it's not the case that it "is-a" CMatrix<T>. Similar deal with Foo and CComplexMat<T>. So inheritance is almost certainly not the correct solution. That leaves: Use friend to allow access bet...
4,821,491
4,821,769
OpenMP: how to flush pointer target?
I’ve just noticed that the following code doesn’t compile in OpenMP (under GCC 4.5.1): struct job { unsigned busy_children; }; job* j = allocateJob(…); // … #pragma omp flush(j->busy_children) The compiler complains about the -> in the argument list to flush, and according to the OpenMP specification it’s right:...
The flush directive has given the OpenMP ARB a headache for a long time. So much so, that there has been talk about removing it completely - though that creates other problems. Using flush(list), is extremely difficult to get correct and even the OpenMP experts have a great deal of trouble getting it correct. The pr...
4,821,612
4,821,665
Code reuse via inheritance and cross-delegation
Assume I have the following class-hierarchy in C++: class AbstractBaseClass { public: // Note: Class is completely abstract! No data! AbstractBaseClass() {} virtual ~AbstractBaseClass() {} virtual std::string definedInVirtual() = 0; virtual std::string definedInDerived() = 0; }; class Virtual : pu...
Code re-use should be implemented through composition, not inheritance. Virtual inheritance is slow and extremely messy and should be avoided in nearly all designs.
4,821,745
4,821,859
How can I write a function template that can accept either a stack or a queue?
I'm implementing four algorithms that are completely identical except for what data structure they use — two use priority_queue, one uses stack, and the last uses queue. They're relatively long, so I'd like to have just one function template that accepts the container type as a template argument and then have each algo...
You can write a non-member top function overloaded on the type of the container adapter: template <typename T> T& top(std::stack<T>& s) { return s.top(); } template <typename T> T& top(std::queue<T>& q) { return q.front(); } // etc. If you actually use a different sequence container with the container adapters (via ...
4,821,913
4,822,059
What advantages does modern Fortran have over modern C++?
I'm trying to decide between Fortran and C++ for an application in scientific computing. It's not clear to me if Fortran still has advantages over other languages when it comes to performance. For example, I believe since Fortran enforces strict aliasing, better optimizations could be made by the compiler when compar...
I took a look at some of the stuff in the latest Fortran standards, and frankly I'm impressed. A lot of what I hated about the language 20 years ago is gone now. No more line numbers and special columns (may they burn in hell). Fortran has been heavily used in engineering circles for 50 years now. That gives you two ad...
4,822,147
4,822,187
C++ - operator delete confusion
I am in the process of learning C++ and am new to the delete operator. As you can see from the code I am applying the delete operator to the new operator (m). After applying it though I am still able to to use the pointer and assign it a new value. I am not receiving any compiler errors. From what I have read, I should...
The delete operator is a bit subtle. When you write delete m; The meaning of this code is "reclaim the memory that m is pointing at." In other words, it does not do anything to the pointer m, but rather to the object m points at. For example, in this diagram: +-----+ m --> | 137 | +-----+ The pointe...
4,822,514
4,822,569
How to save a directed acyclic graph to disk?
So, I have created a directed acyclic graph in c++, now I want to save it to a text file, or maybe files. How do I do that? P.S: sorry for confusion... I mean to ask how to format the file. Thanks in advance!
A simple way is to save first all nodes assigning to each of them a node ID, then save all arcs using the node ID of starting and ending node. This will handle all cases (including non-connected graphs, multiply connected graphs, loops... etc.)
4,822,606
4,822,672
Boilerplate typedefs for STL-compatible container
Is there, within the standard library or Boost, some kind of utility base class for populating a custom STL-compatible Sequence with the required typedefs (size_type, value_type, etc...). I'm thinking of something like boost::iterator_facade, but for containers. I was going to roll-up my own, but wanted to make sure su...
even if it does exist, you still have to typedef typename base::size_type size_type. does not seem you would gain much.
4,822,613
4,822,646
C++ function exported in dll and loaded from C#
I have in C++: void __declspec(dllexport) foo(HWND wnd) And in C# [DllImport("MyDll.dll", CharSet = CharSet.Ansi)] public static extern void foo(IntPtr wnd); When I'm trying to call it I have this error - Additional information: Unable to find an entry point named 'foo' in DLL. I tried to inspect the dll and I hav...
You need to disable C++ name mangling. Declare your native function like this: extern "C" __declspec(dllexport) void foo(HWND wnd) You can use the dumpbin.exe utility to see DLL exports as well.
4,822,996
4,823,027
Restrictions on local variable usage in C++?
I had a few questions in a technical interview that I thought I knew, but wanted to double-check (they said I passed it, but I was unsure about these): A variable declared inside a Class Method... Can that be used outside of that method, like for instance in another method? (I said no) Can a variable declared inside a...
A variable within a class method, that's instantiated within that method and wholly contained within that method, can only be used within that method. Its lifetime is finite. Edit: to clarify, I'm not saying it can't be passed to another function call within the function scope and I'm not talking about instantiating...
4,823,020
4,823,046
function call not accepting my arguments
I am getting the following error when I try to call a function that I have overloaded to accept cuComplex which is a structure from CUDA. ../common/Filter.cpp:73: error: no matching function for call to ‘ReaderIF::getData(float2&, int&)’ ../readers/ReaderIF.h:63: note: candidates are: virtual bool ReaderIF::getData(cuC...
You have indexed your pointer, which has dereferenced it, so it is no longer a cuComplex *, but a cuComplex. Perhaps you want to do the following: hhReader->getData(&h_hhBuff[r*cols], r);
4,823,050
4,823,085
How do I know which function will be called?
Today I found the following disturbingly ambiguous situation in our code base: class Base { public: virtual void Irrelevant_Function(void) = 0; protected: C_Container * Get_Container(void); }; class A : public Base, public Not_Important { public: inline C_Container * Get_Container(void); }; class B ...
It depends how you're calling the function. If you're calling through an A *, an A & or an A, then you'll be calling A::Get_Container(). If you're calling through a Base *, a Base & (even if they point to/reference an A), then you'll be calling Base::Get_Container().
4,823,487
4,823,491
Is there a good general purpose options class for c++?
Each time I write another one of my small c++ toy programs, I come across the need for a small, easy-to-use options/parameter class. Here is what it should be able to do: accept at least ints, doubles, string parameters easy way to add new options portable, small and fast free read options from a file and/or command l...
Boost Program-Options is pretty slick. I think it does all the things on your list, apart from maybe bounds validation. But even then, you can provide custom validators pretty easily. Update: As @stefan rightly points out in a comment, this also fails on "small"! It adds quite a significant chunk to your binary if y...