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
2,561,242
2,579,243
shared memory STL maps
I am writing an Apache module in C++. I need to store the common data that all childs need to read as a portion of shared memory. Structure is kind of map of vectors, so I want to use STL map and vectors for it. I have written a shared allocator and a shared manager for the purpose, they work fine for vectors but not f...
Please post the line on which you initialize spIndex. The compiler error 'does not have class type' generally means that you're referring to a function as though it were a field, which in this case probably means that your compiler has mistaken spIndex for a function somehow. I haven't seen the code, but I bet the Mo...
2,561,368
2,561,377
Illegal token on right side of ::
I have the following template declaration: template <typename T> void IterTable(int& rIdx, std::vector<double>& rVarVector, const std::vector<T>& aTable, const T aValue, T aLowerBo...
My guess is that max has been made a macro. This happens at some point inside windows.h. Define NOMINMAX prior to including to stop windows.h from doing that. EDIT: I'm still confident this is your problem. (Not including <limits> would result in a different error). Place #undef max and #undef min just before the funct...
2,561,471
2,561,535
Is there any cross-platform threading library in C++?
I'm looking for some easy to use cross-platform threading library written in C++. What's your opinion on boost::thread or Pthreads? Does Pthreads run only on POSIX compliant systems? What about the threading support in the Qt library?
Boost.Thread is the draft for the coming standard threading library of the C++ language. Knowing that, I prefer to use it as it provide some strong guarantees (because it becomes standard). Update: Now that we have the standard threading libraries, some more precisions. Some boost constructs, like boost::shared_mutex,...
2,561,594
2,561,742
GDI polyline partial output when printing
I'm seeing a strange problem when calling Win32 GDI Polyline() when printing out. On screen it all looks ok, however if printing it will stop the polyline when it encounters a large value. I think this discrepency is due to the scaling for printing yielding larger POINT values. It appears as if the polyline stops d...
According to MS documentation, this would occur in Windows 9X, where the coordinates are 32-bit but the underlying implementation is 16-bit and the values are just truncated. In practice, I already had the same problem years ago in non-9X Windows versions, but the situation was a bit different from yours, I believe. My...
2,561,726
2,894,877
How to get MAC address of bluetooth HID device?
how can I get the MAC address of a bluetooth device which connected as HID device? I have handle to the device Handle = CreateFile(didetail->DevicePath, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL); but I can't find how to get the MAC address. C++; Windows
At first I was going to say you should pipe the results of ipconfig/all into a file, but then I found this: http://www.codeguru.com/cpp/i-n/network/networkinformation/article.php/c5451/Three-ways-to-get-your-MAC-address.htm Scroll halfway down to GetAdaptersInfo, that should be what you're looking for.
2,561,799
2,561,817
NULL pointer comparison fails
I'm initializing in a class a pointer to be NULL. Afterwards I check if it is NULL in the same class. But it's not always 0x0. Sometimes it's 0x8 or 0xfeffffff or 0x3f800000 or 0x80 or other strange stuff. In most case the pointer is 0x0 but sometimes it gets altered somehow. I'm sure that I'm not changing it anywhere ...
This: MeshObject::MeshObject(const MeshObject &_copyFromMe) is a copy constructor. Because it is a constructor, it too should be setting the vertexColors member to some known & hopefully valid value, but it isn't, unless the value in the thing being copied is not NULL. But what if it is NULL? Basically, your if() need...
2,561,927
2,564,763
Converting C++ string/wchar_t* to C# string?
Question: I need to call a C# dll from a C++ executable. I use COM, and it works fine for int, long and bool. But I can't get a string along... The IDL file says it's a BSTR, but I can't pass it correctly, and neither retrieve one. I tried using wchar_t* and using sysalloc as I did with VB6, but that doesn't seem to wo...
If you're using ATL you can do this: std::string theString = "hello"; CComBSTR bstr(theString.c_str()); DoSomething(bstr); // Function that takes a BSTR as an argument Or if no ATL: const wchar_t* theString = L"hello"; BSTR bstr = SysAllocString(theString); DoSomething(bstr); SysFreeString(bstr);
2,562,099
2,562,111
Why is only the second array dimension important?
Why when working with two dimensional arrays only second dimension is important for a compiler? Just can't get my head around that. Thanks
Because compiler needs to figure out how to access the data from memory. The first dimension is not important because compiler can count the number of items when all other sizes are given. Examples: int a1[] = { 1, 2, 3, 4 } compiler knows to allocate space for 4 integers. Now, with this: int a2[][] = { 1, 2, 3, 4, 5,...
2,562,176
2,562,194
Storing a type in C++
Is it possible to store a type name as a C++ variable? For example, like this: type my_type = int; // or string, or Foo, or any other type void* data = ...; my_type* a = (my_type*) data; I know that 99.9% of the time there's a better way to do what you want without resorting to casting void pointers, but I'm curious i...
No, this is not possible in C++. The RTTI typeid operator allows you to get some information about types at runtime: you can get the type's name and check whether it is equal to another type, but that's about it.
2,562,320
2,565,037
Specializing a template on a lambda in C++0x
I've written a traits class that lets me extract information about the arguments and type of a function or function object in C++0x (tested with gcc 4.5.0). The general case handles function objects: template <typename F> struct function_traits { template <typename R, typename... A> struct _internal { }; t...
I think it is possible to specialize traits for lambdas and do pattern matching on the signature of the unnamed functor. Here is the code that works on g++ 4.5. Although it works, the pattern matching on lambda appears to be working contrary to the intuition. I've comments inline. struct X { float operator () (float ...
2,562,373
2,562,488
Is it good to have a member template function inside a non-template class in c++?
I wonder if it is a good practice to have a member template function inside a non-template class in c++? Why? I'm trying to do something like this in classA.h: classA { public: member_func1(); member_func2(); }; in classA.cpp: template <class T> share_func(); classA::member_func1() { call share_func...
That's a perfectly legitimate use of template functions. Additionally, there's no problem with using templated member functions of a non-template class. For example: class A { public: void say_hello() { cout << "Hello World" << endl; } template<T> print_it( T arg ) { cout << "Argument: " << arg << endl; } ...
2,562,540
2,562,560
Pointers in For loops
Quick question: I am a C# guy debugging a C++ app so I am not used to memory management. In the following code: for(int i = 0; i < TlmMsgDB.CMTGetTelemMsgDBCount(); i++) { CMTTelemetryMsgCls* telm = TlmMsgDB.CMTGetTelemetryMsg(i); CMT_SINT32_Tdef id = telm->CMTGetPackingMapID(); ManualScheduleTables.Set...
There is no global answer for this question. It really depends on how the person implemented the function with the return value. It may return a variable allocated on the heap and expect you to delete it It may return a member variable pointer not even on the heap If its return value is on the heap, TlmMsgDB may do i...
2,562,906
2,563,542
Ways std::stringstream can set fail/bad bit?
A common piece of code I use for simple string splitting looks like this: inline std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } r...
I can't imagine what errors this person thinks might happen, and you should ask them to explain. Nothing can go wrong except allocation errors, as you mentioned, which are thrown and not swallowed. The only thing I see that you're directly missing is that ss.fail() is guaranteed to be true after the while loop, becaus...
2,563,165
2,563,184
C++ explicit template specialization of templated constructor of templated class
I have a class like template <class T> struct A{ template <class U> A(U u); }; I would like to write an explicit specialization of this for a declaration like A<int>::A(float); In the following test code, if I comment out the specialization, it compiles with g++. Otherwise, it says I have the wrong number of ...
Try template <> template <> A<int>::A(int t, float *u){ *u += float(2*t); } That seems to work for me.
2,563,227
2,563,242
what is the best way to use global variables in c++?
For me, I usually make a global class with all members static. All other classes will inherit from this global class. I wonder if this is a good practice? Anybody got any suggestions?
Generally try to avoid global variables as they introduce global state. And with global state you do not have referential transparency. Referential transparency is a good thing and global state is a bad thing. Global state makes unit tests pretty pointless for example. When you have to though, I'd agree that mos...
2,563,254
2,563,261
Why do I have to provide default ctor?
Why do I have to provide default ctor if I want to create an array of objects of my type? Thanks for answers
Because they have to be initialized. Consider if it wasn't the case: struct foo { foo(int) {} void bar(void) {} }; foo a[10]; foo f = a[0]; // not default-constructed == not initialized == undefined behavior Note you don't have to: int main(){ // initializes with the int constructor foo a[] = {1, 2, 3}...
2,563,398
2,563,475
How to keep unreachable code?
I'd like to write a function that would have some optional code to be executed or not depending on user settings. The function is cpu-intensive and having ifs in it would be slow since the branch predictor is not that good. My idea is making a copy in memory of the function and replace NOPs with a jump when I don't wan...
You can cut the cost of the branch by up to 10, just by moving it out of the loop: int Test() { int x = 2; if (should_skip) { for (int i=0 ; i<10 ; i++) { x *= 2; x *= 2; } } else { for (int i=0 ; i<10 ; i++) { x *= 2; x...
2,563,666
2,564,300
Normal C++ code in Qt doesnt build and run
I am using Qt under linux, if it matters. I ran successfully under Geany (a simple c++ compiler) the following: //my first program in C++ Hello World! #include <iostream> using namespace std; int main () {cout << "Hello World!"; return 0;} I opened Qt source file and copied the exact same code and i can't build or r...
If you did what I think you did, you didn't open this as a project, which is the only place where you can build and run (I think). Try the following. - Open Qt Creator. - Go to File->New File or Project - At the bottom, select "Qt4 Console Application" - Select a location; it might be nice to create a folder called...
2,563,701
2,563,710
array loop not working correctly? c++
Trying to count how many elements within the array are not equal to 0, is something set up wrong? I'd like to check all values in the array (it's a sudoku board) and then when all elements are "full" I need to return true. Is something off? bool boardFull(const Square board[BOARD_SIZE][BOARD_SIZE]) { int totalCount...
You have = rather than == if (totalCount == 81) is the correct line. Doing this with a single "=" actually assigns the value 81 to totalCount, so your test is essentialy: if (81) And since in C++ anything nonzero is true, this is always true
2,563,737
2,563,768
In the following implementation of static_strlen, why are the & and parentheses around str necessary?
If I change the type to const char str[Len], I get the following error: error: no matching function for call to ‘static_strlen(const char [5])’ Am I correct that static_strlen expects an array of const char references? My understanding is that arrays are passed as pointers anyway, so what need is there for the element...
No, the function parameter is a reference to an array of Len const chars. That's how the function knows the length (assuming the last byte is a NUL terminator, hence the -1). The parentheses are there precisely to stop it being what you think it is. Actually there's no such thing in C++ as an array of references, so it...
2,563,874
2,563,925
delete a file in protected mode env(like windows xp)
I write a program to delete a file from somewhere of my harddisk in 8086 but when i use int 21h (ah=41h) an error happens and carry set to 1.and I cannot delete that. does anyone know what can I do? I think it should be from protected mode which does not allow my program to delete another file.I want the answer and lan...
If you assemble and link your program to as a DOS executable, it should work (provided the code is correct for DOS, of course). My guess is that you're assembling and linking it to a Windows executable. In that case, you need to use the Windows DeleteFile function to delete the file.
2,563,979
2,563,987
Invalid use of 'void' in C++ when using struct and classes
I have 1 compiler error. It is from this line in my code: cout << myClass->Get_Type().description; Where as Get_Type() is: void Tile::Get_Type() { return &myStruct; } I'm not quite sure what I am doing wrong. Or what for that matter could be going wrong.
A function with a return type of void cannot return anything (that's what the void means: the function does not return anything). You are trying to return something (the address of myStruct). You either need to return nothing (i.e. change your return to just be return; or remove it entirely) or change the return type...
2,564,135
2,564,327
Should every class have its own namespace?
Something that has been troubling me for a while: The current wisdom is that types should be kept in a namespace that only contains functions which are part of the type's non-member interface (see C++ Coding Standards Sutter and Alexandrescu or here) to prevent ADL pulling in unrelated definitions. Does this imply that...
To avoid ADL, you need only two namespaces: one with all your classes, and the other with all your loose functions. ADL is definitely not a good reason for every class to have its own namespace. Now, if you want some functions to be found via ADL, you might want to make a namespace for that purpose. But it's still qu...
2,564,200
2,564,796
Why might stable_sort be affecting my hashtable values?
I have defined a struct ABC to contain an int ID, string NAME, string LAST_NAME; My procedure is this: Read in a line from an input file. Parse each line into first name and last name and insert into the ABC struct. Also, the struct's ID is given by the number of the input line. Then, push_back the struct into a vect...
Let's see. It can be one of these things: Your hashtable implementation is broken. Your hash function is broken. Somehow sorting changes the semantic value of what you've stored. A sorted vector certainly has different values than an unsorted vector. In reality, it doesn't matter which one of these are the cause of t...
2,564,218
2,564,229
How to combine ASCII text files, then encrypt, then decrypt, and put into a 'File' Class? C++
For example, if I have three ASCII files: file1.txt file2.txt file3.txt ...and I wanted to combine them into one encrypted file: database.txt Then in the application I would decrypt the database.txt and put each of the original files into a 'File' class on the heap: class File{ public: string getContents(); ...
Just use a zip file? You can of course roll your own header meta data to store the filenames, but this particular wheel has been re-invented enough times. If you need better encryption than that provided by zlib, then you can either use the crypt functions in your platform, or it's very easy to implement something lik...
2,564,503
2,564,741
How do I check if my program has data piped into it
Im writing a program that should read input via stdin, so I have the following contruct. FILE *fp=stdin; But this just hangs if the user hasn't piped anything into the program, how can I check if the user is actually piping data into my program like gunzip -c file.gz |./a.out #should work ./a.out #should exit program...
Since you're using file pointers, you'll need both isatty() and fileno() to do this: #include <unistd.h> #include <stdio.h> int main(int argc, char* argv[]) { FILE* fp = stdin; if(isatty(fileno(fp))) { fprintf(stderr, "A nice msg.\n"); exit(1); } /* carry on... */ return 0; } ...
2,564,605
2,564,665
C or C++ Win32 How can I obtain the number of threads running in my program?
On Win32, how can a C++ program determine how many threads are active in my program's process? Is there an API call?
You can use Tool Help API to enumerate the current processes running and within each process the threads running. Of course by the time you have completed the analysis more tasks and threads may have started and others may have ended.
2,564,952
2,565,030
How does the below program work in c++?
I have just created 2 pointers which has undefined behavior and try to invoke a class member function which has no object created ? I don't understand this? #include<iostream> using namespace std; class Animal { public: void talk() { cout<<"I am an animal"<<endl; } }; class Dog : public Animal { public:...
A) It's undefined behavior. Any behavior may happen. B) Since you're not calling a virtual method, it's pretty easy to explain why the undefined behavior actually does this (and I've tested this under just about every compiler I could find). In C++, calling a member method is equivalent (in practice if not in defini...
2,565,068
2,565,141
Classes, constructor and pointer class members
I'm a bit confused about the object references. Please check the examples below: class ListHandler { public: ListHandler(vector<int> &list); private: vector<int> list; } ListHandler::ListHandler(vector<int> &list) { this->list = list; } Because of the internal vector<int> list; definition, here I would be w...
It depends on whether you want to share the underyling vector or not. In general, I think it is a good practice to avoid sharing wherever possible, since it removes the question of object ownership. Without sharing: class ListHandler { public: ListHandler(const std::vector<int>& list) : _list(list) {} ...
2,565,097
2,565,191
Higher-kinded Types with C++
This question is for the people who know both Haskell (or any other functional language that supports Higher-kinded Types) and C++... Is it possible to model higher kinded types using C++ templates? If yes, then how? EDIT : From this presentation by Tony Morris: Higher-order Polymorphism : Languages such as Java and C...
Template-template parameters? template <template <typename> class m> struct Monad { template <typename a> static m<a> mreturn(const a&); template <typename a, typename b> static m<b> mbind(const m<a>&, m<b>(*)(const a&)); }; template <typename a> struct Maybe { bool isNothing; a value; }; ...
2,565,240
2,565,825
What is a NULL value
I am wondering , what exactly is stored in the memory when we say a particular variable pointer to be NULL. suppose I have a structure, say typdef struct MEM_LIST MEM_INSTANCE; struct MEM_LIST { char *start_addr; int size; MEM_INSTANCE *next; }; MEM_INSTANCE *front; front = (MEM_INSTANCE*)malloc(size...
There are many good contributed answers which adequately address the questions. However, the coverage of NULL is light. In a modern virtual memory architecture, NULL points to memory for which any reference (that is, an attempt to read from or write to memory at that address) causes a segfault exception—also called an...
2,565,299
2,565,309
Using ASSERT and EXPECT in GoogleTest
While ASSERT_* macros cause termination of test case, EXPECT_* macros continue its evaluation. I would like to know which is the criteria to decide whether to use one or the other.
Use ASSERT when the condition must hold - if it doesn't the test stops right there. Use this when the remainder of the test doesn't have semantic meaning without this condition holding. Use EXPECT when the condition should hold, but in cases where it doesn't we can still get value out of continuing the test. (The test ...
2,565,354
2,581,048
Varying performance of MSVC release exe
I am curious what could be the reason for highly varying performance of the same executable. Sometimes, I run it and it takes 20 seconds and sometimes it is 110. Source is compiled with MSVC in Release mode with standard options. The code is here: vector<double> Un; vector<double> Ucur; double *pUn, *pUcur; ... // time...
Issue was resolved when I switched the arguments in this function from addresses to variables. Before I had double &time, double &dt, double &end_time Now: double time, double dt, double end_time It appears to be memory-related issue... Hope, it helps anybody
2,565,512
2,565,522
Actual long double precision does not agree with std::numeric_limits
Working on Mac OS X 10.6.2, Intel, with i686-apple-darwin10-g++-4.2.1, and compiling with the -arch x86_64 flag, I just noticed that while... std::numeric_limits<long double>::max_exponent10 = 4932 ...as is expected, when a long double is actually set to a value with exponent greater than 308, it becomes inf--ie in re...
It's because 1e309 is a literal that gives a double. You need to use a long-double literal 1e309L.
2,565,527
2,565,547
valgrind complains doing a very simple strtok in c
Hi I'm trying to tokenize a string by loading an entire file into a char[] using fread. For some strange reason it is not always working, and valgrind complains in this very small sample program. Given an input like test.txt first second And the following program #include <stdio.h> #include <string.h> #include <stdlib...
Your buffer size should be filesize + 1. The +1 is for the null char. filesize = fsize(argv[1]); char buffer[filesize + 1]; Also fread does not put a \0 at the end of the string. So you'll have to do it yourself as: fread(buffer,sizeof(char),filesize,fp); buffer[filesize] = 0;
2,565,556
2,565,612
Prevent committing code with svn if certain obsolete C/C++ functions are used
Is there a way to prevent developers from committing code when certain unsafe or obsolete functions are used? For example: scanf atoi gets etc..
A project I've worked uses a simple set of macros in a header that's included in every file (some compilers let you specify such a header on the command line, so you can force it's use in a makefile): #define strcpy strcpy_is_banned_use_strlcpy #define strcat strcat_is_banned_use_strlcat #define strncpy strncpy_is_ba...
2,565,661
2,565,720
wopen calls when porting to Linux
I have an application which was developed under Windows, but for gcc. The code is mostly OS-independent, with very few classes which are Windows specific because a Linux port was always regarded as necessary. The API, especially that which gets called as a direct result of user interaction, is using wide char arrays i...
The strategy I took on Mac hinges on the fact that Mac OS X uses utf-8 in all its file io POSIX api's. I thus created a type "fschar" thats a char in windows non unicode builds, wchar_t in windows UNICODE builds and char (again) when building for Mac OS. I pass around all file system strings using this type. String lit...
2,566,167
2,566,182
Where to find __sync_add_and_fetch_8?
I got errors when trying to use __sync_add_and_fetch: test8.cpp:(.text+0x90e): undefined reference to `__sync_add_and_fetch_8' collect2: ld returned 1 exit status Please kindly advise how to rectify this. Specs: GCC/G++: 4.4.1 GNU/Linux 2.6.32 SMP i686 Many thanks! EDIT: In addition to the answer provided, one can use...
That function is not supported on all x86 architectures. Try specifying your architecture, such as --with-arch=pentium4.
2,566,200
2,566,318
Passing array by ref
Ref. to my last post and sellibitze's comment to that post on passing array by ref rather than by value, why is it that when I'm passing array by value compiler can deduce arguments but it won't do it if I pass it by value? template<class T,int row, int col> void invert(T (&a)[row][col]) //NOTE AMPERSAND in main with ...
That's because when you pass an array "by value" it decays to a pointer. That is, you are in fact passing a pointer to the first element without any size information. When you have a signature like this: void foo(int arr[10]); then the value 10 is completely ignored and you can pass arrays of ints of any size to it. ...
2,566,213
2,566,270
test cases for testing a strtok-alike function [C++]
Consider the following class definition: class StrToTokens { StrToTokens(const char* str, const char* delimiters = "\t\r\n"); //constructor string getNextToken(); void reset(); bool empty(); } Can someone list some good testcases to test the above class. A few I could think of are: empty string, empty delimite...
Well, I usually add at least one testcase that just tests for a normal working case. And of course all the tests you guys mentioned where just for the constructor. The other methods have to be tested as well: does reset really reset (what is reset meant to do anyway) does empty behave as expected are tokens retrieved ...
2,566,278
2,566,296
How to see the code generated by the compiler
Guys in one of excersises (ch.5,e.8) from TC++PL Bjarne asks to do following: '"Run some tests to see if your compiler really generates equivalent code for iteration using pointers and iteration using indexing. If different degrees of optimization can be requested, see if and how that affects the quality of the gener...
You want to write code something like this: int a[] = {1,2,3,4}; int n = 0; for ( int i = 0; i < 4; i++ ) { n += a[i]; } int * p = a; for ( int i = 0; i < 4; i++ ) { n += *p++; } Then you need to compile it with compiler options that gets your compiler to emit assembly language, and take a look at it. It's als...
2,566,307
2,574,925
WTL Child window event handling
I am developing window application in that I am having 2 child windows on left and right side. I want to handle input events for both windows separately. How to achieve it? My code: class EditorWindow : public DxWindow { public: CSplitterWindow m_vSplit; CPaneContainer m_lPane; CPaneContainer m_rPane; ...
WTL::CSplitterWindow and WTL::CPaneContainer do not forward the WM_KEYxxx and WM_MOUSExxx messages to their parent. Derive your EditorWindow from WTL::CSplitterWindowImpl and your Panes from WTL::CPaneContainerImpl for instance: class CMyPaneContainer : public CPaneContainerImpl<CMyPaneContainer> { public: DECLARE...
2,566,841
2,566,861
Pointers into elements in a container
Say I have an object: struct Foo { int bar_; Foo(int bar) bar_(bar) {} }; and I have an STL container that contains Foos, perhaps a vector, and I take // Elsewhere... vector<Foo> vec; vec.push_back(Foo(4)); int *p = &(vec[0].bar_) This is a terrible idea, right? The reason is that vector is going to be ...
The standard specifies when such pointers are invalidated. References into a vector die when you increase its size past capacity or add/remove a preceding element. References into a deque are invalidated if you add/remove from the middle. Otherwise, references and iterators are safe to keep for the lifespan of the unde...
2,566,884
2,566,955
Why boost::recursive_mutex is not working as expected?
I have a custom class that uses boost mutexes and locks like this (only relevant parts): template<class T> class FFTBuf { public: FFTBuf(); [...] void lock(); void unlock(); private: T *_dst; int _siglen; int _processed_sums; int _expected_sums; ...
Try this: template<class T> void FFTBuf<T>::lock() { std::cerr << "Locking" << std::endl; _mut.lock(); std::cerr << "Locked" << std::endl; } template<class T> void FFTBuf<T>::unlock() { std::cerr << "Unlocking" << std::endl; _mut.unlock(); } You use the same instance of unique_lock _lock twice an...
2,567,557
2,567,692
injecting dll into exe file
I want to execute an exe file which is written in VC++.net 2008 in a computer which has windows xp and has not .net framework and none of c++ libraries. but when i run the file i get this error: This application has failed to start because the application configuration is incorrect.... I want a way to put all dependen...
If you are writing a pure C++ application (Win32 only, no .NET), then you want to staticly link the C++ run time, which can be changed in your project's properties. See this answer for the instructions. (It is for VC2005, but the steps are the same in VC2008)
2,567,589
2,567,593
What is the difference between these usages: new SubElement() and SubElement()?
Into a class constructor, I need to create some objects on the fly and add them to a vector. Here is my code: ContainerClass::ContainerClass() { for (int i = 0; i < limit; i++) elements.push_back(SubElement()); } Is this the same thing with new SubElement()? Do I still need to free those SubElement() objects ...
Method 1: If you have std::vector<SubElement> elements; Then you would use elements.push_back(SubElement()). SubElement() creates a SubElement on the stack and then a copy gets added to the vector. You should NOT call delete on the individual elements of the vector. They will be destructed and deallocated when the v...
2,567,666
2,567,685
Referencing invalid memory locations with C++ Iterators
I am a big fan of GCC, but recently I noticed a vague anomaly. Using __gnu_cxx::__normal_iterator (ie, the most common iterator type used in libstdc++, the C++ STL) it is possible to refer to an arbitrary memory location and even change its value without causing an exception! Is this expected behavior? If so, isn't a s...
Dereferencing an iterator beyond the end of the container from which it was obtained is undefined behavior, and doing nothing is just a possibility there. Note that this is a question of compromise, it is nice having iterators check for validity for development, but that adds extra operations to the code. In MSVS itera...
2,567,693
2,567,727
including a string as a parameter to a function in a header file? c++
I have this header file, zeeheader.h, and I wrote some classes in it, I'm having problems giving a string as a parameter to one of the functions: class DeliTest { public: void DeliCheck(Stack*,string); void ComCheck (unsigned,string); bool EofCheck (unsigned,string); }; As I was implementing it in the cp...
Make sure to #include <string>, and because strings are in the std namespace, you should declare your strings as std::string in the header. As a sidenote, make sure you do NOT declare using namespace std; in your header files. This would cause any other headers or c/cpp files that include this header to also use the s...
2,567,784
2,567,802
C++ Operator overloading - 'recreating the Vector'
I am currently in a collage second level programing course... We are working on operator overloading... to do this we are to rebuild the vector class... I was building the class and found that most of it is based on the [] operator. When I was trying to implement the + operator I run into a weird error that my profess...
This: int operator[ ](int); is a non-const member function. It means that it cannot be called on a const Vector. Usually, the subscript operator is implemented such that it returns a reference (if you return a value, like you are doing, you can't use it as an lvalue, e.g. you can't do newone[j] = temp_2_int; like you...
2,567,847
2,567,858
C++ Libraries similar to C#?
I'm coming to C++ from a .Net background. Knowing how to use the Standard C++ Libraries, and all the syntax, I've never ventured further. Now I'm looking learning a bit more, such as what libraries are commonly used? I want to start getting into Threading but have no idea to start. Is there a library (similar to how...
For C++, Boost is your everything. Threading and networking are among the things it offers. But there's much more: Smart pointers Useful containers not found in the STL, such as fixed-size arrays and hashtables Closures Date/time classes A foreach construct Min/max functions Command line option parsing Regular express...
2,567,906
2,567,927
Returning a local object from a function
Is this the right way to return an object from a function? Car getCar(string model, int year) { Car c(model, year); return c; } void displayCar(Car &car) { cout << car.getModel() << ", " << car.getYear() << endl; } displayCar(getCar("Honda", 1999)); I'm getting an error, "taking address of temporary". Shoul...
getCar returns a Car by value, which is correct. You cannot pass that return value, which is a temporary object, into displayCar, because displayCar takes a Car&. You cannot bind a temporary to a non-const reference. You should change displayCar to take a const reference: void displayCar(const Car& car) { } Or, you ...
2,567,980
2,568,016
std::binary_function - no match for call?
include #include <functional> using namespace std; int main() { binary_function<double, double, double> operations[] = { plus<double>(), minus<double>(), multiplies<double>(), divides<double>() }; double a, b; int choice; cout << "Enter two numbers" << endl; cin >> a >> b; cout << "Enter opcode: 0...
std::binary_function only contains typedefs for argument and return types. It was never intended to act as a polymorphic base class (and even if it was, you'd still have problems with slicing). As an alternative, you can use boost::function (or std::tr1::function) like this: boost::function<double(double, double)> oper...
2,567,997
2,568,180
Using a checked STL implementation, anything available for free?
Have you used a checked STL implementation? Did it find bugs you were not expecting? Is there one I can try on Linux for free?
The GNU implementation of the standard C++ library that comes with GCC has checked STL. Just add -D_GLIBCXX_DEBUG to your command line. Yes, I've used it. I can't say for sure if it's caught bugs but it gives me more confidence that certain classes of bugs aren't being missed. Because of performance overhead, we only...
2,568,194
2,568,331
Populate a vector with all multimap values with a given key
Given a multimap<A,B> M what's a neat way to create a vector<B> of all values in M with a specific key. e.g given a multimap how can I get a vector of all strings mapped to the value 123? An answer is easy, looping from lower->upper bound, but is there a neat loop-free method?
Here's the way to do it STL style : // The following define is needed for select2nd with DinkumWare STL under VC++ #define _HAS_TRADITIONAL_STL 1 #include <algorithm> #include <vector> #include <map> #include <string> #include <functional> #include <map> #include <iterator> #include <iostream> using namespace std; v...
2,568,230
2,569,086
C++ STL vector iterator... but got runtime error
I'm studying STL and made win32 project.. But I got stuck in runtime error.. I tried to debug it but.. (partial code) vector<Vertex> currPoly=polygons.back(); vector<Vertex>::iterator it; for(it=currPoly.begin();it!=currPoly.end();++it){ vector<Vertex>::iterator p1; vector<Vertex>::iterator n1; vector<Ver...
You should be a little more clear about exactly what your question is... If it's that you're wondering why values for n1 and tmp can't be displayed in the debugger, I'm guessing that it's because you're debugging a release build (or some kind of build with optimizations), and the compiler has probably 'optimized away' ...
2,568,243
2,568,275
Linker error when compiling boost.asio example
I'm trying to learn a little bit C++ and Boost.Asio. I'm trying to compile the following code example: #include <iostream> #include <boost/array.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: client <host>" <<...
you need to link against libboost_system and apparently also against libboost_thread. g++ -I /usr/local/boost_1_42_0 -lboost_system -lboost_thread a.cpp in case of multi-threaded libraries: g++ -I /usr/local/boost_1_42_0 -lboost_system-mt -lboost_thread-mt a.cpp
2,568,294
2,568,322
Is it a good idea to create an STL iterator which is noncopyable?
Most of the time, STL iterators are CopyConstructable, because several STL algorithms require this to improve performance, such as std::sort. However, I've been working on a pet project to wrap the FindXFile API (previously asked about), but the problem is it's impossible to implement a copyable iterator around this AP...
An input iterator which is not a forward iterator is copyable, but you can only "use" one of the copies: incrementing any of them invalidates the others (dereferencing one of them does not invalidate the others). This allows it to be passed to algorithms, but the algorithm must complete with a single pass. You can tell...
2,568,446
2,573,596
What are the best (portable) cross-platform arbitrary-precision math libraries?
I’m looking for a good arbitrary precision math library in C or C++. Could you please give me some advices or suggestions? The primary requirements: It must handle arbitrarily big integers—my primary interest is on integers. In case that you don’t know what the word arbitrarily big means, imagine something like 100000...
GMP is the popular choice. Squeak Smalltalk has a very nice library, but it's written in Smalltalk. You asked for relevant books or articles. The tricky part of bignums is long division. I recommend Per Brinch Hansen's paper Multiple-Length Division Revisited: A Tour of the Minefield.
2,568,612
2,569,669
Linking with Boost error
I just downloaded and ran the boost installer for version 1.42 (from boostpro.com), and set up my project according to the getting started guide. However, when I build the program, I get this linker error: LINK : fatal error LNK1104: cannot open file 'libboost_program_options-vc90-mt-gd-1_42.lib' The build log adds t...
There's a slight difference between the documentation and my actual installation. Where the documentation has "boost_1_42_0" in the path, the installer made my path "boost_1_42". With that fixed, it works.
2,568,933
2,569,573
Upper bound for custom rand48
I'm using a custom random number function rand48 in CUDA. The function does not allow an upperbound to be set, but I require the output to be between 0 and 1. I guess I'm missing something but how would I convert the output to be between 0 and 1, the length of the number can change e.g. 697135872 would need to be div...
If your PRNG behaves like rand then it generates numbers between 0 and RAND_MAX with uniform probability. You just have to multiply by 1.f/RAND_MAX. If you divide by different numbers in different cases, you will end up with non-uniform distribution.
2,568,996
2,569,017
What container type provides better (average) performance than std::map?
In the following example a std::map structure is filled with 26 values from A - Z (for key) and 0 - 26 for value. The time taken (on my system) to lookup the last entry (10000000 times) is roughly 250 ms for the vector, and 125 ms for the map. (I compiled using release mode, with O3 option turned on for g++ 4.4) But if...
For your example, use int value(char x) { return x - 'a'; } More generalized, since the "keys" are continuous and dense, use an array (or vector) to guarantee Θ(1) access time. If you don't need the keys to be sorted, use unordered_map, which should provide amortized logarithmic improvement (i.e. O(log n) -> O(1)) to m...
2,569,046
2,569,211
Is there a way to increase the efficiency of shared_ptr by storing the reference count inside the controlled object?
This is becoming a common pattern in my code, for when I need to manage an object that needs to be noncopyable because either A. it is "heavy" or B. it is an operating system resource, such as a critical section: class Resource; class Implementation : public boost::noncopyable { friend class Resource; HANDLE s...
A partial solution is to use make_shared to create your shared_ptrs. For example, auto my_thing = std::make_shared<Thing>(); instead of auto my_thing = std::shared_ptr<Thing>(new Thing); It's still non-intrusive, so nothing else needs to change. Good implementations of make_shared combine the memory allocation for ...
2,569,234
2,569,259
Problems with delete in destructor
I wrote this code. The constructor works normally, but in the destructor I get "Windows has triggered a breakpoint." How should I correct this? template class CyclicalArray { private: T* mem_ptr; public: CyclicalArray(size_t capacity, const T& default_value) { this->default_value = default_value; this->...
If you're going to perform placement new, you need to do it on raw memory. Something like: template class CyclicalArray { private: T* mem_ptr; public: CyclicalArray(size_t capacity, const T& default_value) { this->default_value = default_value; this->capacity = capacity; head_index = 0; mem_ptr...
2,569,576
2,569,588
How to create a const boost matrix?
How can I create a const boost matrix? The following did not work: const boost::numeric::ublas::matrix<double> arrayM(1, 3) = { {1.0, 2.0, 3.0} };
Usually something akin to: typedef boost::numeric::ublas::matrix<double> matrix_type; const matrix_type get_matrix(void) { matrix_type result(1, 3); result(0, 0) = 1; result(0, 1) = 2; result(0, 2) = 3; return result; } const matrix_type arrayM = get_matrix(); You might also try something like ...
2,569,602
2,569,618
Is there a practical benefit to casting a NULL pointer to an object and calling one of its member functions?
Ok, so I know that technically this is undefined behavior, but nonetheless, I've seen this more than once in production code. And please correct me if I'm wrong, but I've also heard that some people use this "feature" as a somewhat legitimate substitute for a lacking aspect of the current C++ standard, namely, the inab...
The first case is not calling anything. It's taking the address. That's a defined, permitted, operation. It yields the offset in bytes from the start of the object to the specified field. This is a very, very, common practice, since offsets like this are very commonly needed. Not all objects can be created on the stack...
2,569,655
2,569,665
How to define a static array without a contant size in a constructor of a class? (C++)
I have a class defined as: class Obj { public: int width, height; Obj(int w, int h); } and I need it to contain a static array like so: int presc[width][height]; however, I cannot define within the class, so it it possible to create a pointer to a 2D array (and, out of curiosity, 3, 4, and 5D arrays), have th...
If, by "dynamic", you mean "heap-allocated", then no, there is no way to this with the current Obj. OTOH, if you know w and h at compile time: template <int W, int H> class Obj { public: // ... private: int presc[W][H]; }
2,569,662
2,569,675
is there a way to use cin.getline() without having to define a char array size before hand?
Basically my task is having to sort a bunch of strings of variable length ignoring case. I understand there is a function strcasecmp() that compares cstrings, but doesn't work on strings. Right now I'm using getline() for strings so I can just read in the strings one line at a time. I add these to a vector of strings, ...
I assume by "convert to cstring" you mean using the c_str() member of string. If that is the case, in most implementation that isn't really a conversion, it's just an accessor. The difference is only important if you are worried about performance (which it sounds like you are). Internally std::strings are (pretty mu...
2,569,695
2,569,791
How can I synchronize database access between a write-thread and a read-thread?
My program has two threads: Main execution thread that handles user input and queues up database writes A utility thread that wakes up every second and flushes the writes to the database Inside the main thread, I occasionally need to make reads on the database. When this happens, performance is not important, but co...
If you don't have more than one main execution thread (ie, the only thread that will push writes onto the worker thread is the same thread that will be reading from the database), then you can probably just have a simple "pending writes" variable/function that you can check before sending a read, and spinlock or wait f...
2,569,738
2,569,751
how to access child instances in a vector in c++
I have a parent class and child class (inherited from parent). In the child class, I have a member function named function_blah(); I used vector<parent*> A to store 5 parent instances, 3 child instances. So the total number of elements in the vector is 8. I can easily access to member functions of element A[0] to A[4],...
You need to downcast the pointer to the child class in order to use child functions on it. When you're accessing a child object using a parent*, you are effectively telling the compiler, "treat this object as a parent". Since function_blah() only exists on the child, the compiler doesn't know what to do. You can amelio...
2,569,782
2,569,819
C++ Exceptions and Inheritance from std::exception
Given this sample code: #include <iostream> #include <stdexcept> class my_exception_t : std::exception { public: explicit my_exception_t() { } virtual const char* what() const throw() { return "Hello, world!"; } }; int main() { try { throw my_exception_t(); } catch (const std::excepti...
When you inherit privately, you cannot convert to or otherwise access that base class outside of the class. Since you asked for something from the standard: §11.2/4: A base class is said to be accessible if an invented public member of the base class is accessible. If a base class is accessible, one can implicitly c...
2,569,940
2,611,899
SFML SetFramerateLimit Not Limiting Frame Rate
Compiler: Visual C++ OS: Windows 7 Enterprise For some reason, Window::SetFramerateLimit isn't limiting the frame rate in the app I'm working on, but it works fine for others. The framerate is capped to 60, but mine jumps around at 100-99 and then goes down to 50 sometimes. It actually causes serious issues. For exampl...
Solved by setting vertical sync to true.
2,570,036
2,570,037
Why does converting from a size_t to an unsigned int give me a warning?
I have the code: unsigned int length = strlen(somestring); I'm compiling with the warning level on 4, and it's telling me that "conversion from size_t to unsigned int, possible loss of data" when a size_t is a typedef for an unsigned int. Why!? Edit: I just solved my own problem. I'm an XP user, and my compiler was ch...
Because unsigned int is a narrower type on your machine than size_t. Most likely size_t is 64 bits wide, while unsigned int is 32 bits wide. EDIT: size_t is not a typedef for unsigned int.
2,570,223
2,570,224
Should a warning or perhaps even an assertion failure be produced if delete is used to free memory obtained using malloc()?
In C++ using delete to free memory obtained with malloc() doesn't necessarily cause a program to blow up. Should a warning or perhaps even an assertion failure should be produced if delete is used to free memory obtained using malloc()? Why did Stroustrup not have this feature on C++?
In C++ using delete to free memory obtained with malloc() doesn't necessarily cause a program to blow up. No, but it does necessarily result in undefined behavior, which means that anything can happen, including the program blowing up or the program continuing to run in what appears to be a correct manner. Do you gu...
2,570,235
2,570,240
Initialize a static member ( an array) in C++
I intended to create a class which only have static members and static functions. One of the member variable is an array. Would it be possible to initialize it without using constructors? I am having lots of linking errors right now... class A { public: static char a[128]; static void do_something(); }; How would ...
You can, just do this in your .cpp file: char A::a[6] = {1,2,3,4,5,6};
2,570,275
2,570,288
Using Visual studio .ncb file for reflection
I am developing visual game level editor in C++. For this I want reflection(RTTI) mechanism to know class attributes at runtime. I am currently using PDB files for this.But using PDB I couldn't retrieve actual code line for extra information in commented format which is given for that attribute. Visual studio uses NCB ...
The NCB file format isn't publicly documented and changes with every version of Visual Studio. With the upcoming VS2010 (due out in about a week and a half), it's going away entirely in favor of a new SQL-based format that should be much easier to work with. Microsoft is also implementing an API for integrating with th...
2,570,551
2,571,533
It won't create a Java VM (JNI)
My simple command line app: int _tmain(int argc, _TCHAR* argv[]) { JavaVM *jvm; JNIEnv *env; JavaVMInitArgs vm_args; JavaVMOption options[1]; options[0].optionString = "-Djava.class.path=."; //Path to the java source code vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6 vm_args.nOptio...
I think that your problem is answered by this question in the Sun JNI FAQ. TL;DR version: Don't move the JVM installation's DLLs.
2,570,552
2,570,593
Why are new()/delete() slower than malloc()/free()?
Why new()/delete() is slower than malloc()/free()? EDIT: Thanks for the answers so far. Please kindly point out specifications of standard C++ implementation of new() and delete() if you have them thanks!
Look at this piece of C code: struct data* pd = malloc(sizeof(struct data)); init_data(pd); The new operator in C++ is essentially doing what the above piece of code does. That's why it is slower than malloc(). Likewise with delete. It's doing the equivalent of this: deinit_data(pd); free(pd); If the constructors ...
2,570,584
2,570,586
iteration on numbers with no 2 same digits
I dont know if it is asked (I couldn't find any). I want to iterate on this kind of numbers implemented on array; int a[10]; int i = 0; for( ; i < 10; i++ ) a[i] = i+1; now the array has "1 2 3 4 5 6 7 8 9 10" and I want to get "1 2 3 4 5 6 7 8 10 9" and then "1 2 3 4 5 6 7 9 8 10" ...
Check std::next_permutation.
2,570,643
2,570,682
Putting a C++ Vector as a Member in a Class that Uses a Memory Pool
I've been writing a multi-threaded DLL for database access using ADO/ODBC for use with a legacy application. I need to keep multiple database connections for each thread, so I've put the ADO objects for each connection in an object and thinking of keeping an array of them inside a custom threadInfo object. Obviously a ...
how do I make the vector allocate from the thread-specific heap? You pass it (at compile-time) an appropriate allocator. Here is a classic on how to do so. If you follow that article's advice (or even just copy the code and adapt it where needed), for a C programmer writing an allocator might be easier than getting r...
2,570,679
2,571,212
Serialization with Qt
I am programming a GUI with Qt library. In my GUI I have a huge std::map. "MyType" is a class that has different kinds of fields. I want to serialize the std::map. How can I do that? Does Qt provides us with neccesary features?
QDataStream handles a variety of C++ and Qt data types. The complete list is available at http://doc.qt.io/qt-4.8/datastreamformat.html. We can also add support for our own custom types by overloading the << and >> operators. Here's the definition of a custom data type that can be used with QDataStream: class Painting ...
2,570,901
2,570,903
Object does not exist after constructor?
I have a constructor that looks like this (in c++): Interpreter::Interpreter() { tempDat == new DataObject(); tempDat->clear(); } the constructor of dataObject does absolutely nothing, and clear does this: bool DataObject::clear() { //clear the object if (current_max_id > 0) { ...
Interpreter::Interpreter() { tempDat == new DataObject(); // <- here tempDat->clear(); } You're using == to assign. Use = instead: tempDat = new DataObject(); Using == gives you an expression that compares the current value of tempDat (some random garbage) to the address of the newly created D...
2,570,959
2,570,973
writing code for nm-alike command [C++]
Out of curiosity about reverse engineering, I am thinking of writing a simple program (in C++) that takes an executable as input and produces the names of all the functions that were a part of source program of that executable. Any pointers on how should I go about it? Step-by-step approach would be much appreciated! E...
Depends heavily on your platform and the origin of the code you're examining. You need a symbol table for the binary you're reversing if you want to get function names out of it. Sometimes that table is embedded in the binary (such as the export lookup table in a DLL), but many times the information simply doesn't exis...
2,571,018
3,521,428
Shaped windows in gtkmm
How do I create shaped windows in Gtkmm. The shape must be defined using cairomm.
Cairo and GTK+ are not directly relevant with shaped windows. You need to look at GDK which is the windowing system for GTK+ Here is the respective method in vanilla (for C) GDK http://library.gnome.org/devel/gtk/stable/GtkWidget.html#gtk-widget-shape-combine-mask
2,571,136
2,571,146
Is it possible to tie a C++ output stream to another output stream?
Is it possible to tie a C++ output stream to another output stream? I'm asking because I've written an ISAPI extension in C++ and I've written ostreams around the WriteClient and ServerSupportFunction/HSE_REQ_SEND_RESPONSE_HEADER_EX functions - one ostream for the HTTP headers and one for the body of the HTTP response....
Yes, you can: out1.tie( & out2 ); where both outs are output streams. out2 will be flushed before output to out1.
2,571,157
2,571,234
Debug-only ostreams in C++?
I've implemented an ostream for debug output which sends ends up sending the debug info to OutputDebugString. A typical use of it looks like this (where debug is an ostream object): debug << "some error\n"; For release builds, what's the least painful and most performant way to not output these debug statements?
How about this? You'd have to check that it actually optimises to nothing in release: #ifdef NDEBUG class DebugStream {}; template <typename T> DebugStream &operator<<(DebugStream &s, T) { return s; } #else typedef ostream DebugStream; #endif You will have to pass the debug stream object as a DebugStre...
2,571,224
2,571,246
Initializing objects on the fly
I have a vector called players and a class called Player. And what I'm trying to do is to write: players.push_back(Player(name, Weapon(bullets))); So I want to be able to create players in a loop. But I see an error message says "no matching function for call Player::Player..." Then I've changed that to: Weapon w(bull...
Change constructor to: Player(const string &name, const Weapon &weapon); or: Player(const string &name, Weapon weapon); It's not valid C++ to initialize a reference with a temporary object, which is what you're doing when you use: Player(name, Weapon(bullets)); it's legal to use a const reference though. EDIT: You s...
2,571,225
2,571,243
Managing libraries and imports in a programming language
I've created an interpreter for a stupid programming language in C++ and the whole core structure is finished (Tokenizer, Parser, Interpreter including Symbol tables, core functions, etc.). Now I have a problem with creating and managing the function libraries for this interpreter (I'll explain what I mean with that la...
If your interpreter is implemented as a library, it is going to be called from other people's C++ code. It's not unreasonable for them to have to call functions in your library from their own code to add function to the interpreter. That's hat my own expression evaluator does. something like this in user code: Interpre...
2,571,265
2,571,284
Overloading delete and retrieving size?
I am currently writing a small custom memory Allocator in C++, and want to use it together with operator overloading of new/ delete. Anyways, my memory Allocator basically checks if the requested memory is over a certain threshold, and if so uses malloc to allocate the requested memory chunk. Otherwise the memory will ...
allocate more memory than neccessary and store the size information there. That's what your system allocator probably does already. Something like this (demonstrate with malloc for simplicity): void *allocate(size_t size) { size_t *p = malloc(size + sizeof(size_t)); p[0] = size; // store the size in t...
2,571,317
2,571,338
C++, constructor restrictions
I'm studing C++ and I can't understand the meaning of the boldface sentence below: From IBM manual: The following restrictions apply to constructors and destructors: Constructors and destructors do not have return types nor can they return values. References and pointers cannot be used on constructors and destructors...
The sentence means that you can't take pointer to a constructor or a destructor. Here's an example: class Sample{ private: int x; public: Sample() { x = 100; }; public: void* member() { x = 200; }; }; template <class X> void call_me(Sample s, X function){ (s.*function)(); }; call_me(s, &Sample::membe...
2,571,402
2,602,693
How to use glOrtho() in OpenGL?
I can't understand the usage of glOrtho. Can someone explain what it is used for? Is it used to set the range of x y and z coordinates limit? glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); It means that the x, y and z range is from -1 to 1?
Have a look at this picture: Graphical Projections The glOrtho command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance. I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus...
2,571,436
2,574,468
Emacs: annoying Flymake dialog box
I have the following lines in my ~/.emacs.d/init.el (custom-set-variables '(flymake-allowed-file-name-masks (quote ( ("\\.cc\\'" flymake-simple-make-init) ("\\.cpp\\'" flymake-simple-make-init))))) (add-hook 'find-file-hook 'flymake-find-file-hook) When I open a C++ file that has a prope...
Easiest way to do this, and still recieve the messages, is to leave the customization variable set to true, and redefine the flymake-display-warning function. ;; Overwrite flymake-display-warning so that no annoying dialog box is ;; used. ;; This version uses lwarn instead of message-box in the original version. ;; ...
2,571,449
2,571,473
How to fix these compiler errors?
I have this source code from 2001 that I would like to compile. It gives this: $ make g++ -O99 -Wall -DLINUX -pedantic -c -o audio.o audio.cpp In file included from audio.cpp:7: audio.h:14: error: use of enum ‘mad_flow’ without previous declaration audio.h:15: error: use of enum ‘mad_flow’ without previous declaratio...
Regarding: I have tried to just insert enum mad_flow {}; ... a correct forward declaration of the type mad_flow would be: enum mad_flow ; But you should really be asking yourself why the declaration or definition is not already visible since the forward declaration is probably a bit of a kludge. Are all the necessa...
2,571,456
2,571,487
Operators overloading for enums
Is it possible to define operators for enums? For example I have enum Month in my class and I would like to be able to write ++my_month. Thanks P.S. In order to avoid overflowing I did something like this: void Date::add_month() { switch(my_month_) { case Dec: my_month_ = Jan; add_year(); ...
Yes it is. Operator overloading can be done for all user defined types. That includes enums.
2,571,620
2,571,654
Encrypt/Decrypt SQLite-database and use it "on the fly"
Here's the thing: In my Qt4.6-Project, I use a SQLite-Database. This database shouldn't be unencrypted on my harddrive. So I want, that on every start of my program, the user gets asked to enter a password to decrypt the database. Of course the database never should appear "in clear" (not encrypted) on my harddrive. So...
There is no built in support, that being said you do have options. 1) You can encrypt/decrypt all of your strings yourselves, but this is a lot of work, is not transparent, and won't allow you to do things like searching in the database. 2) SQLiteCrypt and SQLCipher do what you're looking for. You can use them almost...
2,571,751
2,571,769
How to provide default argument as this object?
I would like to have declaration like this: void Date::get_days_name(const Date& = this) which I would understand that if no argument is provided use this object as an argument. For some reason in VS I'm getting err msg: 'Error 1 error C2355: 'this' : can only be referenced inside non-static member ' Any idea w...
You could make overloaded function: void get_days_name(const Date&) const; void get_days_name() const { get_days_name(*this); } (BTW, this is a pointer, not a reference.)
2,571,816
2,572,087
Is it possible to define enumalpha?
I would like to be able to write: cout << enumalpha << Monday; and get printed on console: Monday P.S. Monday is an enum type.
Okay, let's go all preprocessor then :) Intended way of use: DEFINE_ENUM(DayOfWeek, (Monday)(Tuesday)(Wednesday) (Thursday)(Friday)(Saturday)(Sunday)) int main(int argc, char* argv[]) { DayOfWeek_t i = DayOfWeek::Monday; std::cout << i << std::endl; // prints Monday std::cin >>...
2,571,831
2,571,839
Can a function return more than one value?
Can a function return more than one value directly (i.e., without returning in parameters taken by-reference)?
No, but you can return a pair or boost::tuple which can contain multiple values. In addition, you can use references to return multiple values like this: void MyFunction(int a, int b, int& sum, int& difference); You would call this function like this: int result_sum; int result_difference; MyFunction(1, 2, result_sum,...
2,571,850
2,571,871
Why does enable_shared_from_this have a non-virtual destructor?
I have a pet project with which I experiment with new features of C++11. While I have experience with C, I'm fairly new to C++. To train myself into best practices, (besides reading a lot), I have enabled some strict compiler parameters (using GCC 4.4.1): -std=c++0x -Werror -Wall -Winline -Weffc++ -pedantic-errors Thi...
A destructor of a class that is intended for subclassing should always be virtual, IMHO. A virtual destructor in a base class is only needed if an instance of the derived class is going to be deleted via a pointer to the base class. Having any virtual function in a class, including a destructor, requires overhead. B...
2,572,409
2,572,425
Does it take time to deallocate memory?
I have a C++ program which, during execution, will allocate about 3-8Gb of memory to store a hash table (I use tr1/unordered_map) and various other data structures. However, at the end of execution, there will be a long pause before returning to shell. For example, at the very end of my main function I have std::cout <...
If the data structures are sufficiently complicated when your program finishes, freeing them might actually take a long time. If your program actually must create such complicated structures (do some memory profiling to make sure), there probably is no clean way around this. You can short cut that freeing of memory by ...
2,572,533
2,572,658
C++ STL-conforming Allocators
What allocators are available out there for use with STL when dealing with small objects. I have already tried playing with pool allocators from Boost, but got no performance improvement (actually, in some cases there was considerable degradation).
You didn't say what compiler you use, but it probably comes with a bunch of pre-built allocators. This is on a Mac with gcc 4.2.1: ~$ find /usr/include/c++/4.2.1/ -name "*allocator*" /usr/include/c++/4.2.1/bits/allocator.h /usr/include/c++/4.2.1/ext/array_allocator.h /usr/include/c++/4.2.1/ext/bitmap_allocator.h /usr/i...