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,528,097
2,528,104
problems with overloaded function members C++
I have declared a class as class DCFrameListener : public FrameListener, public OIS::MouseListener, public OIS::KeyListener { bool keyPressed(const OIS::KeyEvent & kEvt); bool keyReleased(const OIS::KeyEvent &kEvt); //*******some code missing************************ }; But if i try defining the members...
The one in the declaration has a reference: bool keyPressed(const OIS::KeyEvent & kEvt); ^! bool DCFrameListener::keyPressed(const OIS::KeyEvent kEvt) ^?
2,528,199
2,528,234
C++ syntax of constructors " 'Object1 a (1, Object1(2))''
I have a such syntax in program /* The Object1 is allowed to be changed */ class Object1 : BaseClass { BaseClass *link; int i; public: Object1(int a){i=a;} Object1(int a, Object1 /*place1*/ o) {i=a; link= &o;} }; int main(){ /* The initialization syntax must be preserved. No any new(), no other lo...
In "place1", you need a reference. Object1 isn't fully defined, so you can't take it by value. That said, you wouldn't want to pass by value; when you take the address of it, you'd be getting the address of the copy, not the actual object. Since you only want a pointer to a BaseClass, it might make more sense to only p...
2,528,274
2,528,296
Native Endians and Auto Conversion
so the following converts big endians to little ones uint32_t ntoh32(uint32_t v) { return (v << 24) | ((v & 0x0000ff00) << 8) | ((v & 0x00ff0000) >> 8) | (v >> 24); } works. like a charm. I read 4 bytes from a big endian file into char v[4] and pass it into the above function as ntoh32 (* ...
The better way, IMHO, is using the htonl and ntohl functions. If you want to be really portable you can not think in terms of "convert to little endian". Rather you should think about "convert to host endian". That's what ntohl is for, if your input is a big-endian for sure (which is what the network standard is). Now,...
2,528,457
2,528,472
Static variables in C and C++
Is there any difference between a variable declared as static outside any function between C and C++. I read that static means file scope and the variables will not be accessible outside the file. I also read that in C, global variables are static . So does that mean that global variables in C can not be accessed in an...
No, there's no difference between C and C++ in this respect. Read this SO answer about what static means in a C program. In C++ there are a couple of other meanings related to the use of static for class variables (instead of instance variables). Regarding global vars being static - only from the point of view of memor...
2,528,542
2,553,611
VS C++ throwing divide by zero exception after a specific check
In the following C++ code, it should be impossible for ain integer division by zero to occur: // gradedUnits and totalGrades are both of type int if (gradedUnits == 0) { return 0; } else { return totalGrades/gradedUnits; //call stack points to this line } however Visual Studio is popping up this error: Unhand...
It turns out this problem was caused by the code I originally had, which did not have the divide-by-zero check, shown here: return totalGrades/gradedUnits; The problem was that although I'd updated the code, I was actually still in the same debug session that threw the original error, so the program was still running ...
2,528,618
2,528,828
C++ invalid reference problem
I'm writing some callback implementation in C++. I have an abstract callback class, let's say: /** Abstract callback class. */ class callback { public: /** Executes the callback. */ void call() { do_call(); }; protected: /** Callback call implementation specific to derived callback. */ virtual void d...
The problem is that in make_callback(), T becomes const std::string&, which in turn becomes T in your singleArgumentCallback. U, however, is a const char*, so a temporary std::string object is created and bound to that reference in singleArgumentCallback. When make_callback() finishes, that temporary is destroyed, leav...
2,528,776
2,529,170
Windows/C++: Is it possible to find the line of code where exception was thrown having "Exception Offset"
One of our users having an Exception on our product startup. She has sent us the following error message from Windows: Problem Event Name: APPCRASH Application Name: program.exe Application Version: 1.0.0.1 Application Timestamp: ...
Yes, that's possible. Start debugging with the exact same binaries as ran by your user, make sure the DLL is loaded and you've got a matching PDB file for it. Look in Debug + Windows + Modules for the DLL base address. Add the offset. Debug + Windows + Disassembly and enter the calculated address in the Address fie...
2,528,780
2,528,806
is multiple inheritance a compiler writers problem? - c++
i have been reading about multiple inheritance What is the exact problem with multiple inheritance? http://en.wikipedia.org/wiki/Diamond_problem http://en.wikipedia.org/wiki/Virtual_inheritance http://en.wikipedia.org/wiki/Multiple_inheritance But since the code does not compile until the ambiguity is resolved, do...
If you want to write code that compiles, you have to know what kind of problems might cause it to not compile and how to avoid these situations. It is your problem, as a user of the compiler, to design your inheritance hierarchies in a way that they will be compilable. Also if you don't understand how multiple inherita...
2,528,995
2,529,011
Remove \r from a string in C++
in a C++ program, there is a point when it reads a string like: "NONAME_1_1\r" the \r is causing me trouble. I guess it prints or adds something like "^M". Is it right? Anyway it casues me problem, and I want to get rid of it. I can not modify the input. I wonder how could I at this point, using C++, and in the easies...
I'm assuming that by string, you mean std::string. If it's only the last character of the string that needs removing you can do: mystring.pop_back(); mystring.erase(mystring.size() - 1); Edit: pop_back() is the next version of C++, sorry. With some checking: if (!mystring.empty() && mystring[mystring.size() - 1] ==...
2,529,046
2,530,733
Change table columns width on resizing window or splitter
Consider there is a QTablWidget and a QTextEdit. Both of them are in a horisontal QSplitte. Let the QTable widget has 2 columns. The problem is to resize the table columns' width as you do resize operation by moving the splitter with mouse. Are there any options to may colums to be resized synchornosly with the table? ...
QHeaderView *header = ui->tableWidget->horizontalHeader(); header->setResizeMode(QHeaderView::Stretch); This code sets all columns of ui->tableWidget to equal width and let it change automatically. And take a look on QHeaderView description in docs, you can do almost anything you can imagine with table columns with th...
2,529,617
2,529,625
How to stop C++ console application from exiting immediately?
Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?
Edit: As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem. That said, I'll...
2,529,770
2,529,997
How to use libraries compiled with MingW in MSVC?
I have compiled several libraries with MingW/MSYS... the generated static libraries are always .a files. When I try to link the library with a MSVC project, Visual Studio throws 'unresolved external symbols' ... It means that the .a static library is incompatible with MS C++ Linker. I presume it has to be converted to ...
Based on this error you put in a comment: error LNK2019: unresolved external symbol "int __cdecl openssl_call(struct ssl_State *,int,int,int)" (?openssl_call@@YAHPAUssl_State@@HHH@Z) referenced in function _main MyAPP.obj all other 4 errors are same only with other functions names Try putting extern "C" a...
2,529,999
2,530,027
What sorting algorithm is this?
Update: OK I see it's a bubble sort, but is it less efficient because it doesn't stop when there's no swap on a particular run? It runs until first is null. Hi, I have a sorting algorithm as follows. My question is, which sorting algorithm is this? I thought it was bubble sort, but it does not do multiple runs. Any ide...
Let's make the algorithm clearer: Sort { first = head; while (first β‰  NULL) { next = first.next while (next β‰  NULL) { if (first.value < next.value) swap first.value and next.value advance next } advance first } } This is a very inefficient implementation o...
2,530,124
2,530,165
How to append to the beginning of a text fle in g++
I want to write to a file without overwriting anything. It is a text file containing records. When I delete a specific record, I do not actually remove it from the file, I just put information in the header saying that it is deleted. How can I do this?
You cannot append to the BEGINNING of a file without having to rewrite it from scratch. It has to go at the end (which makes sense, since that's what the word "append" means). If you want to be able to flag a record as deleted without reserving space for that flag, you'll need to place the information at the end, or re...
2,530,180
2,530,187
Question about Null vs zero
I have this function: void ToUpper(char * S) { while (*S!=0) { *S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S; S++; } } What does it mean for *S != 0, should it be null instead?
That is checking for the end of the string which is a character which has the value of zero. It is not connected to NULL pointers in any way.
2,530,274
2,530,351
How to overwrite only part of a file in c++
I want to make modifications to the middle of a text file using c++, without altering the rest of the file. How can I do that?
If the replacement string is the same length, you can make the change in place. If the replacement string is shorter, you may be able to pad it with zero-width spaces or similar to make it the same number of bytes, and make the change in place. If the replacement string is longer, there just isn't enough room unless ...
2,530,286
2,530,321
I need to create a very large array of bits/boolean values. How would I do this in C/C++?
Is it even possible to create an array of bits with more than 100000000 elements? If it is, how would I go about doing this? I know that for a char array I can do this: char* array; array = (char*)malloc(100000000 * sizeof(char)); If I was to declare the array by char array[100000000] then I would get a segmentation fa...
If you are using C++, std::vector<bool> is specialized to pack elements into a bit map. Of course, if you are using C++, you need to stop using malloc.
2,530,443
2,530,468
Is modifying a file without writing a new file possible in c++?
Let's say I have a text file that is 100 lines long. I want to only change what is in the 50th line. One way to do it is open the file for input and open a new file for output. Use a for-loop to read in the first half of the file line by line and write to the second file line by line, then write what I want to change...
Open the file, use fseek to jump to the place you need and write the data, then close the file. from http://www.cplusplus.com/reference/clibrary/cstdio/fseek/... #include <stdio.h> int main () { FILE * pFile; pFile = fopen ( "example.txt" , "r+" ); fputs ( "This is an apple." , pFile ); fseek ( pFile , 9 , SEE...
2,530,466
2,530,472
funny looking comments - c++
when i read through source files of opensource projects i often come across some weird phrases in the comments /* @brief ...... @usage..... @remarks.... @par.... */ questions 1.What are they?(were not mentioned when i was learning c++) 2.Do they have any documentation(where)
They are just comments and as such have no special meaning in C++. They are probably to allow a documentation generator (For example Doxygen) to extract the data from the comments.
2,530,624
2,530,633
Why won't gcc compile a class declaration as a reference argument?
This compiles fine in Visual studio, but why not in XCode? class A() {}; someMethod(A& a); someMethod(A()); //error: no matching function call in XCode only :( Is this bad form? it seems annoying to have to write the following every time: A a; someMethod(a); //successful compile on Xcode Am i missing something?...
You cannot bind a temporary to a non-const reference. It would work if you changed the function to take a const reference: someMethod(const A& a); In addition, A a(); does not declare a local variable. It declares a function named a that takes no parameters and returns an object of type A. You mean: A a;
2,530,650
2,530,661
Multiple variables in switch statement in c
How to write following statement in c using switch statement in c int i = 10; int j = 20; if (i == 10 && j == 20) { Mymethod(); } else if (i == 100 && j == 200) { Yourmethod(); } else if (i == 1000 || j == 2000) // OR { Anymethod(); } EDIT: I have changed the ...
In general you can't. What you are doing already is fine, although you might want to add an else clause at the end to catch unexpected inputs. In your specific example it seems that j is often twice the value of i. If that is a general rule you could try to take advantage of that by doing something like this instead: i...
2,530,691
2,530,706
Using a method of an abstract class
is it possible to use a method of an abstract class? how can i use a method of a class without having an instance?
If you declare a method as static, you can call it directly without needing a class instance. Otherwise you will need to have an instance of a derived class. Since an abstract class cannot be instantiated directly, you cannot call a method of an abstract class directly unless it is a static method. But you can call a ...
2,530,738
2,530,753
How to read in space-delimited information from a file in c++
In a text file I will have a line containing a series of numbers, with each number separated by a space. How would I read each of these numbers and store all of them in an array?
std::ifstream file("filename"); std::vector<int> array; int number; while(file >> number) { array.push_back(number); }
2,530,796
2,530,816
issue with std::advance on std::sets
I've stumbled upon what I believe is a bug in the stl algorithm advance. When I'm advancing the iterator off of the end of the container, I get inconsistent results. Sometimes I get container.end(), sometimes I get the last element. I've illustrated this with the following code: #include <algorithm> #include <cstdio>...
When I'm advancing the iterator off of the end of the container, ... ... you get undefined behavior. Whatever happens then, is fine according to the C++ standard. That could be much worse than inconsistent results.
2,530,806
2,794,213
Problem with displaying graphs on a Qt canvas
Let's say I'm a Qt newbie. I want a good Qt library for displaying simple graphs. I've found the quanava library. But there is a problem. When I compiled a basic example it looks like graph edges are not painted properly when moving nodes. I don't have any idea where is a bug but this code seems to be rather simple. I ...
Ok, first of all saying graph i mean mathematical concept G=(V,E). I improved quanava library, which is a very good starting point for graph visualization.
2,530,842
2,530,889
Calling a constructor to reinitialize variables doesn't seem to work?
I wanted to run 1,000 iterations of a program, so set a counter for 1000 in main. I needed to reinitialize various variables after each iteration, and since the class constructor had all the initializations already written out - I decided to call that after each iteration, with the result of each iteration being store...
Your line Class(); does call the constructor of the class Class, but it calls it in order to create a "temporary object". Since you don't use that temporary object, the line has no useful effect. Temporary objects (usually) disappear at the end of the expression in which they appear. They're useful for passing as funct...
2,530,843
2,530,857
Deriving a class from an abstract class (C++)
I have an abstract class with a pure virtual function f() and i want to create a class inherited from that class, and also override function f(). I seperated the header file and the cpp file. I declared the function f(int) in the header file and the definition is in the cpp file. However, the compiler says the derived ...
The functions f() and f(int) do not have the same signature, so the second would not provide an implementation for the first. The signatures of the PVF and the implementation must match exactly.
2,530,864
2,531,041
gcc precompiled headers weird behaviour with -c option
Short story: I can't make precompiled headers work properly with gcc -c option. Long story: Folks, I'm using gcc-4.4.1 on Linux and before trying precompiled headers in a really large project I decided to test them on simple program. They "kinda work" but I'm not happy with results and I'm sure there is something wrong...
Ok, I think I've found the solution: -fpch-preprocess should be used alongside with -c option. It works like a charm! Here's the timings: with pch $ time g++ -I. -include pre.h -c foo.cpp -fpch-preprocess real 0m0.028s user 0m0.016s sys 0m0.016s without pch $ time g++ -I. -c foo.cpp real 0m0.330s user 0...
2,530,996
2,531,006
Custom http service responds fine to local IP address but NOT to localhost or 127.0.0.1
I'm trying to connect to a custom http service written by another developer. The service responds fine on a local IP address and port number. Such as: http://10.1.1.1:1234 but it does NOT respond to http://localhost:1234 or http://127.0.0.1:1234 The service is a simple single function application written in VC++ that ...
The HTTP server socket is bound to the network ip of the server. It needs to be bound to all the interfaces on the host machine. (this will include the loopback interface, localhostor 127.0.0.1)
2,531,000
2,531,089
C++ whats the difference between uint64 and *uint64?
Why does: const char example; (uint64*)example have a value of 140734799798420 and *(uint64*)example have a value of 7004431430466964258 p.s. dont worry about the type cast, I am interested why the second * increases the value. Thanks
As others have said, you've invoked undefined behavior. No particular behavior is guaranteed. That said, you see different values because you are printing different locations in memory -- the first prints data from the memory location where example is stored, and the second prints data from the memory location stored ...
2,531,063
2,531,092
virtual methods and template classes
I got over a problem, I think a very specific one. I've got 2 classes, a B aseclass and a D erived class (from B aseclass). B is a template class ( or class template) and has a pure virtual method virtual void work(const T &dummy) = 0; The D erived class is supposed to reimplement this, but as D is Derived from B rath...
You placed the const in the wrong place. Try virtual void work(int* const &dummy){ /* put work code here */ } const int* is the same as int const*, i.e. it associates the const with the int and not the pointer.
2,531,359
2,531,397
Do condition variables still need a mutex if you're changing the checked value atomically?
Here is the typical way to use a condition variable: // The reader(s) lock(some_mutex); if(protected_by_mutex_var != desired_value) some_condition.wait(some_mutex); unlock(some_mutex); // The writer lock(some_mutex); protected_by_mutex_var = desired_value; unlock(some_mutex); some_condition.notify_all(); But if p...
Imagine the following scenario: | Thread 1 | Thread 2 | | if(protected_by_mutex_var != desired_value) -> true | | | | atomic_set(pro...
2,531,515
2,531,522
Can someone explain this "endian-ness" function for me?
Write a program to determine whether a computer is big-endian or little-endian. bool endianness() { int i = 1; char *ptr; ptr = (char*) &i; return (*ptr); } So I have the above function. I don't really get it. ptr = (char*) &i, which I think means a pointer to a character at address of where i is ...
If you have a little-endian architecture, i will look like this in memory (in hex): 01 00 00 00 ^ If you have a big-endian architecture, i will look like this in memory (in hex): 00 00 00 01 ^ The cast to char* gives you a pointer to the first byte of the int (to which I have pointed with a ^), so the value pointed t...
2,531,848
2,531,856
How can I round money values to the nearest $5.00 interval?
I have an Informix-SQL based Pawnshop app which calculates an estimate of how much money should be loaned to a customer, based on the weight and purity of gold. The minimum the pawnshop lends is $5.00. The pawnshop employee will typically lend amounts which either ends with a 5 or 0. examples: 10, 15, 20, 100, 110, 125...
I'd just divide by 5, round to the appropriate integer, and multiply by 5. There might be an easier way but that would work.
2,531,968
2,531,992
Intermediate values in C++
I can not find how to implement a design in C++. In the language of Delphi in case the operator can write the following design: case s[j] of '0'..'9','A'..'Z','a'..'z','_': doSomeThing(); How can i do the same in c++. Attracts me is the construction type 'a' .. 'z' and etc... Thank you
The short answer is that it is impossible. You can simulate a list of values like this: switch (s[j]) { case '0': case '1': case '2': case '3': doSomething1(); break; case 'a': case 'b': case 'c': case 'd': doSomething2(); break; } But you cannot specify ranges. You should use if-else-if if you need ra...
2,532,105
2,532,111
question regarding "this" pointer in c++
i have been given class with int variables x and y in private, and an operator overload function, class Bag{ private: int x; int y; public: Bag(); ~Bag(); //....... //.....etc }; Bag operator+ (Bag new) const{ Bag result(*this); //what does this mean? result.x += new.x; ...
Bag result(*this) creates a copy of the object on which the operator function was called. Example if there was: sum = op1 + op2; then result will be a copy of op1. Since the operator+ function is doing a sum of its operands and returning the sum, we need a way to access the operand op1 which is done through the this...
2,532,107
2,532,119
Why are data members private by default in C++?
Is there any particular reason that all data members in a class are private by default in C++?
Because it's better to be properly encapsulated and only open up the things that are needed, as opposed to having everything open by default and having to close it. Encapsulation (information hiding) is a good thing and, like security (for example, the locking down of network services), the default should be towards go...
2,532,290
2,532,297
How to compile and build c++ application with hand written makefile in windows?
Can someone provide a HelloWorld demo ?
There's an nmake tutorial available here (nmake is what comes with visual studio). Is there something more specific you're trying to do? It would help get a better answer. Are there some specific differences with Windows that concern you?
2,532,412
2,532,418
When is .h not needed to include a header file?
This works: #include <iostream> using namespace std; but this fails: #include <stdio> When is .h not needed? About the namespace issue,I didn't find such logic in cstdio: #pragma once #ifndef _CSTDIO_ #define _CSTDIO_ #include <yvals.h> #ifdef _STD_USING #undef _STD_USING #include <stdio.h> #define _STD_USING #...
It's not needed for the header files defined by the C++ Standard, none of which have a .h extension. The C++ version of stdio.h is: #include <cstdio> which wraps stdio.h, placing the names in it in the C++ std namespace, but you can still use all the C Standard header files in C++ code, if you wish. Edit: The macro th...
2,532,422
2,532,428
Conversion of pointer-to-pointer between derived and base classes?
Regarding the following C++ program: class Base { }; class Child : public Base { }; int main() { // Normal: using child as base is allowed Child *c = new Child(); Base *b = c; // Double pointers: apparently can't use Child** as Base** Child **cc = &c; Base **bb = cc; return 0; } GCC ...
If this was allowed, you could write this: *bb = new Base; And c would end up pointing to an instance of Base. Bad.
2,532,454
2,543,150
Subclassing and adding data members
I have an hierarchy of classes that looks like the following: class Critical { public: Critical(int a, int b) : m_a(a), m_b(b) { } virtual ~Critical() { } int GetA() { return m_a; } int GetB() { return m_b; } void SetA(int a) { m_a = a; } void SetB(int b) { m...
My suggestion: find the most patient person you work with who is familiar with this code, and ask them some of these questions. I assume you are not posting a more complete example because of IP concerns. That makes it hard to provide good advice. Based on your first code sample, I would say just use structs with pub...
2,532,495
2,532,577
C++ struct, public data members and inheritance
Is it ok to have public data members in a C++ class/struct in certain particular situations? How would that go along with inheritance? I've read opinions on the matter, some stated already here practices on when to implement accessors on private member variables rather than making them public Accessors vs. public memb...
If you have a data structure that isn't intended to have behaviour but genuinely is nothing more than a pure struct in the C sense, particularly if each instance of it is only used internally to the implementation of other "proper" classes, then it is fine to make it a struct and have public fields. After all, as you'v...
2,532,534
2,533,911
C++ Professional Code Analysis Tools
I would like to ask about the available (free or not) Static and Dynamic code analysis tools that can be used to C++ applications ESPECIALLY COM and ActiveX. I am currently using Visual Studio's /analyze compiler option, which is good and all but I still feel there is lots of analysis to be done. I'm talking about a C+...
Without a doubt you want to use Axman. This is by far the best ActiveX/Com security testing tool available, and its open source. This was one of the leading tools used in the Month Of Browser Bugs by H.D. Moore, who is also the creator of Metasploit. I I have personally used Axman to find vulnerabilities and write ...
2,532,542
2,532,658
What does using mean in c++?
Like : using ::size_t; using ::fpos_t; using ::FILE; In fact it's a question inspired by the comment under this question: When is .h not needed to include a header file?
This is called using declaration. There are actually two ways you can use the using keyword. There is a third special form of using declarations used inside class definitions, but i'll focus on the general using declaration here. (see below). using declaration using directive These have two very different effects. A ...
2,532,625
2,532,691
Remove from a std::set<shared_ptr<T>> by T*
I have a set of shared pointers: std::set<boost::shared_ptr<T>> set; And a pointer: T* p; I would like to efficiently remove the element of set equal to p, but I can't do this with any of the members of set, or any of the standard algorithms, since T* is a completely different type to boost::shared_ptr<T>. A few appr...
Construct a shared_ptr<T> from T with a null_deleter (see boost:::shared_ptr FAQ). struct null_deleter { void operator()(void const *) const { } }; size_t remove_ptr_from_set(std::set<boost::shared_ptr<T>> &set, X* x) { shared_ptr<X> px(x, null_deleter()); return set.erase(px); } That way the types are c...
2,532,714
2,532,781
Does replacing statements by expressions using the C++ comma operator could allow more compiler optimizations?
The C++ comma operator is used to chain individual expressions, yielding the value of the last executed expression as the result. For example the skeleton code (6 statements, 6 expressions): step1; step2; if (condition) step3; return step4; else return step5; May be rewritten to: (1 statement, 6 expres...
Most compilers will break your code down into "basic blocks", which are stretches of code with no jumps/branches in or out. Optimisations will be performed on a graph of these blocks: that graph captures all the control flow in the function. The basic blocks are equivalent in your two versions of the code, so I doubt t...
2,532,725
2,532,741
gcc returns error with nested class
I am attempting to use the fully qualified name of my nested class as below, but the compiler is balking! template <class T> class Apple { //constructors, members, whatevers, etc... public: class Banana { public: Banana() { //etc... } //other constructors, members, etc......
That's probably not what you do in your code. The error message looks like you do this Apple<K>::Banana freshBanana = someVar.returnsABanana(); The compiler has to know before it parses the code whether a name names a type or not. In this case, when it parses, it cannot know because what type K is, is not yet known (y...
2,532,907
2,532,917
Combining C++ and C#
Is it a good idea to combine C++ and C# or does it pose any immediate issues? I have an application that needs some parts to be C++, and some parts to be C# (for increased efficiency). What would be the best way to achieve using a native C++ dll in C#?
Yes using C# and C++ for your product is very common and a good idea. Sometimes you can use managed C++, in which case you can use your managed C++ module just like any other .NET module. Typically you'd do everything that you can in C#. For the parts you need to do in C++ you'd typically create a C++ DLL and then ca...
2,532,983
2,533,095
Free Cryptography libraries
What are the most stable and useful Cryptography libraries, that they are: written with/for python, c++, c#, .net opensource, GNU, or other free license
The standard Python library (implementing common ciphers like AES and RSA) is PyCrypto. It doesn't support things like PKCS yet, however. There is a partial Python wrapper for the Crypto++ library given by PyCryptopp, which you may find useful. The OpenSSL library is also wrapped for Python by PyOpenSSL. A Python imple...
2,533,132
2,574,342
How to get this Qt state machine to work?
I have two widgets that can be checked, and a numeric entry field that should contain a value greater than zero. Whenever both widgets have been checked, and the numeric entry field contains a value greater than zero, a button should be enabled. I am struggling with defining a proper state machine for this situation. S...
After reading your requirements and the answers and comments here I think merula's solution or something similar is the only pure Statemachine solution. As has been noted to make the Parallel State fire the finished() signal all the disabled states have to be final states, but this is not really what they should be as...
2,533,353
2,533,361
How do you make a private member in the base class become a public member in the child class?
Consider the following code: class Base { void f() { } }; class Derived: public Base { public: }; What can you change in the derived class, such that you can perform the following: Derived d; d.f(); If the member is declared as public in the base class, adding a using declaration for Base::f in the derived cl...
This is not possible. A using declaration can't name a private base class member. Not even if there are other overloaded functions with the same name that aren't private. The only way could be to make the derived class a friend: class Derived; class Base { void f() { } friend class Derived; }; class Derived:...
2,533,464
2,534,401
How to Join N live MP3 streams into one using FFMPEG?
How to Join N live MP3 streams (radio streams like such live KCDX mp3 stream http://mp3.kcdx.com:8000/stream ) into 1 using FFMPEG? (I have N incoming live mp3 streams I want to join them and stream out 1 live mp3 stream) I mean I want to mix sounds like thay N speakers speak at the same time (btw N stereo to 1 mono), ...
It looks like url_fopen(), defined in avio.h, is the function you are looking for.
2,533,476
2,533,500
What will happen when I call a member function on a NULL object pointer?
I was given the following as an interview question: class A { public: void fun() { std::cout << "fun" << std::endl; } }; A* a = NULL; a->fun(); What will happen when this code is executed, and why? See also: When does invoking a member function on a null instance result in undefined behavior?
It's undefined behavior, so anything might happen. A possible result would be that it just prints "fun" since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).
2,533,481
2,533,543
Analog of Java Form Layout in Qt
Once I have programmed GUI with Java and have used Form Layouts. Form layout (if I am not mistaken that is from SWT library) made possible to give right, left, top and bottom adges of any GUI element (widget) with respect to other widgets in the same widget (parent widget) or with respect to the adges of parent widget....
It's hard to understand what you need exactly, but Qt has a plethora of layout options. QFormLayout, it so happens, is not what you need here (it's meant for forms in the web-sense: labels with text input boxes). But QBoxLayout (and its subclasses) and QGridLayout probably are what you need. I was always able to satisf...
2,533,580
2,533,928
Creating and using a static lib in xcode
I am trying to create a static library in xcode and link to that static library from another program. So as a test i have created a BSD static C library project and just added the following code: //Test.h int testFunction(); //Test.cpp #include "Test.h" int testFunction() { return 12; } This compiles fine and create ...
Are you sure that the libraries source file is named Test.cpp and not Test.c? With .c i get exactly the same error. If it is Test.c you need to add extern "C" to the header for C++. E.g.: #ifdef __cplusplus extern "C" { #endif int testFunction(); #ifdef __cplusplus } #endif See e.g. the C++ FAQ lite entry for more d...
2,533,728
2,533,964
c++ floating point precision loss: 3015/0.00025298219406977296
The problem. Microsoft Visual C++ 2005 compiler, 32bit windows xp sp3, amd 64 x2 cpu. Code: double a = 3015.0; double b = 0.00025298219406977296; //*((unsigned __int64*)(&a)) == 0x40a78e0000000000 //*((unsigned __int64*)(&b)) == 0x3f30945640000000 double f = a/b;//3015/0.00025298219406977296; the result of calcul...
Are you using directx in your program anywhere as that causes the floating point unit to get switched to single precision mode unless you specifically tell it not to when you create the device and would cause exactly this
2,533,774
2,533,778
Measuring execution time of a call to system() in C++
I have found some code on measuring execution time here http://www.dreamincode.net/forums/index.php?showtopic=24685 However, it does not seem to work for calls to system(). I imagine this is because the execution jumps out of the current process. clock_t begin=clock(); system(something); clock_t end=clock(); cout<<"E...
Have you considered using gettimeofday? struct timeval tv; struct timeval start_tv; gettimeofday(&start_tv, NULL); system(something); double elapsed = 0.0; gettimeofday(&tv, NULL); elapsed = (tv.tv_sec - start_tv.tv_sec) + (tv.tv_usec - start_tv.tv_usec) / 1000000.0;
2,534,449
2,534,501
What are the parts that a good C++ project should contain? (Docs, Makefile, Tests etc...)
i am writing my bachelor thesis and there is some C++ code attached to it. I want to have a nice clean Project. So what should be in it ? I think : Documentation in html ( generated with Doxygen) README File Makefile ( which make ? CMake ? ) Unit-Tests ( which unit test framework? ) Copyright Text ? ... Did i miss s...
Simplify the list: Documentation in a place and form that can easily be found and read, including instructions on how to build it; instructions on how to use it. Some sort of confidence testing ("I compiled it, but does it work?"). Whether the docs are HTML, plain text or in-source comments; whether there's a Make...
2,534,502
2,557,239
Is there a good graph layout library callable from C++?
The (directed) graphs represent finite automata. Up until now my test program has been writing out dot files for testing. This is pretty good both for regression testing (keep the verified output files in subversion, ask it if there has been a change) and for visualisation. However, there are some problems... Basically...
Although the answers so far were worth an upvote, I can't really accept any of them. I've still been searching, though. One thing I found is AGLO. The code is GPL v1, but there are papers that describe the algorithms, so it should be easy enough to re-implement from scratch if necessary. There's also the paper by Gansn...
2,534,507
2,534,631
Semi-generic function
I have a bunch of overloaded functions that operate on certain data types such as int, double and strings. Most of these functions perform the same action, where only a specific set of data types are allowed. That means I cannot create a simple generic template function as I lose type safety (and potentially incurring ...
Use sfinae template<typename> struct restrict { }; template<> struct restrict<string> { typedef void type; }; template<> struct restrict<int> { typedef void type; }; template <typename T> typename restrict<T>::type foo(T bar); That foo will only be able to accept string or int for T. No hard compile time error occurs...
2,534,607
2,534,670
Multimap erase doesn't work
following code doesn't work with input: 2 7 add Elly 0888424242 add Elly 0883666666 queryname Elly querynum 0883266642 querynum 0888424242 delnum 0883666666 queryname Elly 3 add Kriss 42 add Elly 42 querynum 42 Why my erase doesn't work? #include<stdio.h> #include<iostream> #include<map> #include <string> using names...
You never move the iterator it in your loop.
2,534,647
2,534,701
Programming help Loop adding
I know this probably really simple but Im not sure what im doing wrong... The assignment states: For the second program for this lab, you are to have the user enter an integer value in the range of 10 to 50. You are to verify that the user enters a value in that range, and continue to prompt him until he does give you ...
The Corrected code is #include <iostream.h> int main () { int num; cout << "do-while Loop Example 2" << endl << endl; do { cout << "Enter a value from 10 to 50: "; cin >> num; if (num < 10 || num > 50) cout << "Out of range; Please try again..." << endl; } while (num < 10...
2,534,815
2,534,830
How to move a struct into a class?
I've got something like: typedef struct Data_s { int field1; int field2; } Data; class Foo { void getData(Data& data); void useData(Data& data); } In another class's function, I might do: class Bar { Data data_; void Bar::taskA() { Foo.getData(data_); Foo.useData(data_); } } Is there a way to m...
You can define the struct inside the class, but you need to do it ahead of the place where you first use it. Structs, like classes themselves, must be forward-declared in order to use them: class Foo { public: struct Data { int field1; int field2; }; void getData(Foo::Data& data) {} ...
2,534,827
2,534,840
What's the outcome if I use free with new or delete with malloc?
It is a compiler error or runtime error? The code below can be compiled! class Base{ void g(); void h(); }; int main() { Base* p = new Base(); free(p); return 0; } However it can't be compiled with a virtual function if I declare the class Base like this class Base{ virtual void g(); void h(); }; The code ...
Undefined outcome, plus malloc() doesn't call constructors and free() doesn't call destructors.
2,535,008
2,535,017
C++ include statement required if defining a map in a headerfile
I was doing a project for computer course on programming concepts. This project was to be completed in C++ using Object Oriented designs we learned throughout the course. Anyhow, I have two files symboltable.h and symboltable.cpp. I want to use a map as the data structure so I define it in the private section of the...
My guess is that you have another file that includes the header file #include "symboltable.h". And that other source file doesn't #include <map> nor #include <string> nor has using namespace std before it includes "symboltable.h". Check which file is being compiled when you get the error. Is it maybe a different so...
2,535,072
2,535,228
Accessing C++ Functions From Text storage
I'm wondering if anyone knows how to accomplish the following: Let's say I have a bunch of data stored in SQL, lets say one of the fields could be called funcName, function name would contain data similar to "myFunction" What I'm wondering is, is there a way I can than in turn extract the function name and actually cal...
Use a macro to define new functions that register themselves automatically. // callable_function.h class CallableFunction { public: virtual void operator()() = 0; }; class CallableFunctionRegistry { public: static CallableFunction *Register(const string &func_name, CallableFun...
2,535,148
2,535,246
"volatile" qualifier and compiler reorderings
A compiler cannot eliminate or reorder reads/writes to a volatile-qualified variables. But what about the cases where other variables are present, which may or may not be volatile-qualified? Scenario 1 volatile int a; volatile int b; a = 1; b = 2; a = 3; b = 4; Can the compiler reorder first and the second, or third ...
The C++ standard says (1.9/6): The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and calls to library I/O functions. In scenario 1, either of the changes you propose changes the sequence of writes to volatile data. In scenario 2, neither change you propose chan...
2,535,218
2,535,233
Process.WaitForExit not triggering with __debugbreak
I'm trying to write a program to test student code against a good implementation. I have a C++ console app that will run one test at a time determined by the command line args and a C# .net forms app that calls the c++ app once for each test. The goal is to be able to detect not just pass/fail for each test, but also...
You should turn of JIT debugging, this page has instructions for how to turn it on or off. Edit You can also use the _CrtSetReportMode and _CrtSetReportFile functions inside the C++ program to change the behaviour of the debug asserts (in particular, you can use _CRTDBG_MODE_FILE to write the contents of the message to...
2,535,284
2,535,307
How can I hash a string to an int using c++?
I have to write my own hash function. If I wanted to just make the simple hash function that maps each letter in the string to a numerical value (i.e. a=1, b=2, c=3, ...), is there a way I can perform this hash on a string without having to first convert it to a c-string to look at each individual char? Is there a more...
Re the first question, sure, e.g, something like: int hash = 0; int offset = 'a' - 1; for(string::const_iterator it=s.begin(); it!=s.end(); ++it) { hash = hash << 1 | (*it - offset); } regarding the second, there are many better ways to hash strings. E.g., see here for a few C examples (easily translatable to C++ a...
2,535,362
2,535,376
How to write a cctor and op= for a factory class with ptr to abstract member field?
I'm extracting files from zip and rar archives into raw buffers. I created the following to wrap minizip and unrarlib: Archive.hpp - Used to access everything. If I could make all the functions in the other classes inaccessible from the outside, I would. (Actually, I suppose I could friend all the other classes in Arch...
First of all you can't "copy" an abstract class because you can't instantiate one. Instead, what you should do is set up a std::tr1::shared_ptr of that class and pass in a pointer. Archive(ArchiveBase *_archiveBase) Use a factory function outside of the Archive class for instantiation. Archive createArchive(string _p...
2,535,370
2,535,634
C++ -- typedef "inside" template arguments?
Imagine I have a template function like this: template<typename Iterator> void myfunc(Iterator a, typename Iterator::value_type b) { ... } Is there a way to implement the same thing by declare a typedef for Iterator::valuetype that I can use in the function signature? For example, I'd prefer to be able to do somethin...
You are looking for a templated typedef to be used inside a templated function definition. I don't think you can do that... You can have a templated class with a static function & typedefs... But using it gets ugly: template<typename Iterator> class arbitraryname { public: typedef typename Iterator::value_type val...
2,535,445
2,535,504
Negative execution time
I wrote a little program that solves 49151 sudoku's within an hour for an assignment, but we had to time it. I thought I'd just let it run and then check the execution time, but it says -1536.087 s. I'm guessing it has to do with the timer being some signed dataype or something, but I have no idea what datatype is used...
If the time was stored in microseconds in a 32-bit signed int, 2758880296 us (microseconds) would produce this result, since 2758880296-2^32 = -1536087000. In minutes and seconds, that's 45:58.880296. (treat those last few decimal places with a grain of salt, since presumably what you printed was rounded to the nearest...
2,535,525
2,535,531
Sending the contents of a file to a client
I am writing a C++ server side application called quote of the day. I am using the winsock2 library. I want to send the contents of a file back to the client, including newlines by using the send function. The way i tried it doesn't work. How would i go about doing this?
Reading the file and writing to the socket are 2 distinct operations. Winsock does not have an API for sending a file directly. As for reading the file, simply make sure you open it in read binary mode if using fopen, or simply use the CreateFile, and ReadFile Win32 API and it will be binary mode by default. Usually y...
2,535,640
2,535,686
maps, iterators, and complex structs - STL errors
So, I have two structs: struct coordinate { float x; float y; } struct person { int id; coordinate location; } and a function operating on coordinates: float distance(const coordinate& c1, const coordinate& c2); In my main method, I have the following code: map<int,person> people; // populate people ...
There's a function in the standard library called std::distance, which operates on iterators. So it looks like the compiler is trying to call that one instead of yours. I'd remove the using namespace std; directive if you're using it, and just say using std::map;, etc.
2,535,783
2,535,789
Simple vector program error
Hi iam new to c++ and iam trying out this vector program and i am getting the following error: error: conversion from test*' to non-scalar typetest' requested| Here is the code #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; class test{ string s; vector <string...
new is used to dynamically allocate memory. You don't need to do that, so just do: test t; // create an instance of test with automatic storage t.read(); // invoke a method The error is because the type of new test() is a test*, a pointer to a (newly created) test. You can't assign a test* to a test. The pointer vers...
2,535,807
2,535,861
How can I fix my program from crashing in C++?
I'm very new to programming and I am trying to write a program that adds and subtracts polynomials. My program sometimes works, but most of the time, it randomly crashes and I have no idea why. It's very buggy and has other problems I'm trying to fix, but I am unable to really get any further coding done since it crash...
When you create your objects with p1(1) and p2(1) the coef array in each object is allocated to contain one element. Then in read() you simply set degreePoly to a (possibly higher) value but don't change the allocation of coef. It will still contain only one element, but all coefficients are written to it, probably wri...
2,535,836
2,535,853
defining < operator for map of list iterators
I'd like to use iterators from an STL list as keys in a map. For example: using namespace std; list<int> l; map<list<int>::const_iterator, int> t; int main(int argv, char * argc) { l.push_back(1); t[l.begin()] = 5; } However, list iterators do not have a comparison operator defined (in contrast to random ...
Parameterise map with a custom comparator: struct dereference_compare { template <class I> bool operator()(const I& a, const I& b) { return *a < *b; } }; map<list<int>::const_iterator, int, dereference_compare> t;
2,535,963
2,535,978
Questions on usages of sizeof
Question 1 I have a struct like, struct foo { int a; char c; }; When I say sizeof(foo), I am getting 8 on my machine. As per my understanding, 4 bytes for int, 1 byte for char and 3 bytes for padding. Is that correct? Given a struct like the above, how will I find out how many bytes will be added as padding? Q...
Answer 1 Yes - your calculation is correct. On your machine, sizeof(int) == 4, and int must be 4-byte aligned. You can find out about the padding by manually adding the sizes of the base elements and subtracting that from the size reported by sizeof(). You can predict the padding if you know the alignment requiremen...
2,536,077
2,536,236
How to optimize erasing from multimap
I have two multimaps defined so multimap phoneNums; and multimap numPhones; they are some kind of phone registry - phoneNums contains Key name, and second argument phonenumber, numPhones contain Key phonenumber and second is name. I want to optimize erase from both of them when i want to delete string Key form phoneNum...
More generally, for this kind of problem, you can use the following technic: A container, which holds the data Several indexes, which point to the data aforementioned If you place reverse indexes along the data (so as to point to the places in the indexes that refer to this item), then you can efficiently remove any ...
2,536,289
2,536,347
Compiler optimization of references
I often use references to simplify the appearance of code: vec3f& vertex = _vertices[index]; // Calculate the vertex position vertex[0] = startx + col * colWidth; vertex[1] = starty + row * rowWidth; vertex[2] = 0.0f; Will compilers recognize and optimize this so it is essentially the following? _vertices[index][0] =...
Yes. This is a basic optimization that any modern (and even ancient) compilers will make. In fact, I don't think it's really accurate to call that you've written an optimisation, since the move straightforward way to translate that to assembly involves a store to the _vertex address, plus index, plus {0,1,2} (multipli...
2,536,615
2,536,690
Generation of an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level
I'd like to generate an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level. Is there such a library in C, C++, PHP or Python to do so? Please kindly advise. Thanks!
The Boost C++ random number library may do some of what you want, certainly you can with some distributions select the modal value of the distribution. That's all I've needed in my own code, so I've never investigated further. The library doesn't generate arrays - you would typically use a C++ std::vector to contain t...
2,537,048
2,537,430
Changing code at runtime
I have a pointer to a function (which i get from a vtable) and I want to edit the function by changing the assembler code (changing a few bytes) at runtime. I tried using memset and also tried assigning the new value directly (something like mPtr[0] = X, mPtr[1] = Y etc.) but I keep getting segmentation fault. How can...
In generally: if memory is allocated with API call VirtualAlloc than you can change the memory attributes with API call VirtualProtect. Check first memory attributes with API call VirtualQuery
2,537,077
2,539,168
cvHaarDetectObjects(): "Stack aound the variable 'seq_thread' was corrupted."
I have been looking in to writing my own implementation of Haar Cascaded face detection for some time now, and have begun with diving in to the OpenCV 2.0 implementation. Right out of the box, running in debug mode, Visual Studio breaks on cvhaar.cpp:1518, informing me: Run-Time Check Failure #2 - Stack aound the vari...
A little debugging revealed the culprit, I believe. I "fixed" it, but this all still seems odd to me. An array of size CV_MAX_THREADS is created on cvhaar.cpp:868: CvSeq* seq_thread[CV_MAX_THREADS] = {0}; On line 918 it proceeds to specify max_threads: max_threads = cvGetNumThreads(); In various places, seq_thread is...
2,537,130
2,537,183
is back_insert_iterator<> safe to be passed by value?
I have a code that looks something like: struct Data { int value; }; class A { public: typedef std::deque<boost::shared_ptr<Data> > TList; std::back_insert_iterator<TList> GetInserter() { return std::back_inserter(m_List); } private: TList m_List; }; class AA { boost::scoped_ptr<A> m_a...
The short answer is yes, back_insert_iterator is safe to pass by value. The long answer: From standard 24.4.2/3: Insert iterators satisfy the requirements of output iterators. And 24.1.2/1 A class or a built-in type X satisfies the requirements of an output iterator if X is an Assignable type (23.1) ... And f...
2,537,132
2,560,851
Windows Programming in C++
Being a C#/Java programmer, I really need to know a fact: Has Windows Programming with Win32SDK/MFC/wxWidget become antiquated? What is the status of popularity of these technologies in software industry now? Being a C#/Java programmer, do I need to learn Win32SDK/MFC/wxWidget now?
Yes, learn Win32, even if don't ever intend to write or maintain C/C++ apps. No, don't bother learning MFC/wxWidget now. MFC does come with its source code, so you can study how some classes implement wrappers for Win32, but that is more interesting to C++ programmers. MFC is has decreased in popularity, though Visua...
2,537,229
2,537,330
How can I write a function template for all types with a particular type trait?
Consider the following example: struct Scanner { template <typename T> T get(); }; template <> string Scanner::get() { return string("string"); } template <> int Scanner::get() { return 10; } int main() { Scanner scanner; string s = scanner.get<string>(); int i = scanner.get<int>(); } Th...
struct Scanner { template <typename T> typename boost::enable_if<boost::is_integral<T>, T>::type get() { return 10; } template <typename T> typename boost::disable_if<boost::is_integral<T>, std::string>::type get() { return "string"; } }; Update "What if I want to accept...
2,537,484
2,537,862
dynamic linking:change of the linking path
Normally it happens that when ever the path of the library that has to be linked dynamically is defined in LD_LIBRARY_PATH or it it will be mentioned with -L flag while creating the binary. In actual scenario if ,lets say the binary has been built and deployed at the client place. Now if there is a change in the path...
Maybe the interviewers wanted to know about dlopen and dlsym? http://linux.die.net/man/3/dlsym
2,537,500
2,537,577
What is the modern equivalent (C++) style for the older (C-like) fscanf method?
What is the best option if I want to "upgrade" old C-code to newer C++ when reading a file with a semicolon delimiter: /* reading in from file C-like: */ fscanf(tFile, "%d", &mypost.nr); /*delimiter ; */ fscanf(tFile, " ;%[^;];", mypost.aftername);/* delimiter ; */ fscanf(tFile, " %[^;]", mypost.forename); /*delimite...
You could overload the right-shift operator on istream for your struct, so: std::istream& operator>>(std::istream& is, mypost_struct& mps) { is >> mps.nr; is.ignore(1, ';'); is.getline(mps.forename, 255, ';'); is.getline(mps.aftername, 255, ';'); is >> mps.dept; is.ignore(1, ';'); is >> mps....
2,537,708
12,783,060
Process Management Solution
I'm working on a project that requires a process management solution much like init.d but with the following requirements: 1) Working with Windows not Linux 2) Must be able to start/stop/restart programs written in heterogeneous languages. 3) Must be able to extend process manager to start / stop processes depending on...
In the end I simply bootstrapped my processes with a Windows service wrapper and manually managed their lifecycle programatically with windows APIs for services.
2,537,716
2,537,825
Why is partial specialization of a nested class template allowed, while complete isn't?
template<int x> struct A { template<int y> struct B {};. template<int y, int unused> struct C {}; ...
My guess as to why this happens: complete specializations are no longer "template classes/functions", they are are "real" classes/methods, and get to have real (linker-visible) symbols. But for a completely-specialized template inside a partially-specialized one, this would not be true. Probably this decision was taken...
2,537,799
2,538,310
How can I convert a Perl regex to work with Boost::Regex?
What is the Boost::Regex equivalent of this Perl regex for words that end with ing or ed or en? /ing$|ed$|en$/ ...
/^[\.:\,()\'\`-]/ should become "^[.:,()'`-]" The special Perl regex delimiter / doesn't exist in C++, so regexes are just a string. In those strings, you need to take care to escape backslashes correctly (\\ for every \ in your original regex). In your example, though, all those backslashes were unnecessary, so I dr...
2,537,819
2,538,879
How to find string in a string
I somehow need to find the longest string in other string, so if string1 will be "Alibaba" and string2 will be "ba" , the longest string will be "baba". I have the lengths of strings, but what next ? char* fun(char* a, char& b) { int length1=0; int length2=0; int longer; int shorter; char end='\0'; while(a[i] != tmp)...
Wow lots of bad answers to this question. Here's what your code should do: Find the first instance of "ba" using the standard string searching functions. In a loop look past this "ba" to see how many of the next N characters are also "ba". If this sequence is longer than the previously recorded longest sequence, save ...
2,537,942
2,537,973
Nullable values in C++
I'm creating a database access layer in native C++, and I'm looking at ways to support NULL values. Here is what I have so far: class CNullValue { public: static CNullValue Null() { static CNullValue nv; return nv; } }; template<class T> class CNullableT { public: CNullableT(CNullValu...
Boost.Optional probably does what you need. boost::none takes the place of your CNullValue::Null(). Since it's a value rather than a member function call, you can do using boost::none; if you like, for brevity. It has a conversion to bool instead of IsNull, and operator* instead of GetValue, so you'd do: void writeToDB...
2,537,947
2,538,007
Example where TYPE_ALIGNMENT() fails
I have a question relating to alignment in C/C++. In Determining the alignment of C/C++ structures in relation to its members Michael Burr posted this macro: #define TYPE_ALIGNMENT( t ) offsetof( struct { char x; t test; }, test ) In the comments someone wrote this might fail with non POD types. Can someone give me a...
offsetof is only specified to work for POD types. If a class contains any data members that are not POD, the class itself is not POD. So, if t in your example is a non-POD type, it is not guaranteed to work. From the C++ standard (18.1/5): The macro offsetof accepts a restricted set of type arguments in this Inter...
2,538,078
2,538,095
What's the bug in the following code?
#include <iostream> #include <algorithm> #include <vector> #include <boost/array.hpp> #include <boost/bind.hpp> int main() { boost::array<int, 4> a = {45, 11, 67, 23}; std::vector<int> v(a.begin(), a.end()); std::vector<int> v2; std::transform(v.begin(), v.end(), v2.begin(), boost::bind(std::multiplies<in...
v2 has a size of zero when you call transform. You either need to resize v2 so that it has at least as many elements as v before the call to transform: v2.resize(v.size()); or you can use std::back_inserter in the call to transform: std::transform(v.begin(), v.end(), std::back_inserter(v2), boost::bind(std::multiplie...
2,538,083
2,602,092
Eclipse CDT: cannot debug or terminate application
I have Eclipse set up fairly nicely to run the G++ compiler through Cygwin. Even the character encoding is set up correctly! There still seems to be something wrong with my configuration: I can't debug. The pause button in the debug view is simply disabled, and no threads appear in my application tree. It seems that gd...
The only workaround that I've found is to start Eclipse directly from Cygwin. Start a Cygwin Bash Shell, navigate to Eclipse's installation directory, and enter ./eclipse.exe. It would appear that there's some problem with the way that CDT communicates with Cygwin; the standard output is passed and kill.exe is executed...
2,538,103
2,538,216
How to call a function from a shared library?
What is the easiest and safest way to call a function from a shared library / dll? I am mostly interested in doing this on linux, but it would be better if there were a platform-independent way. Could someone provide example code to show how to make the following work, where the user has compiled his own version of foo...
NOTE: You are passing C++ objects (in this case STL strings) around library calls. There is no standard C++ ABI at this level, so either try to avoid passing C++ objects around, or ensure that both your library and your program have been built with the same compiler (ideally the same compiler on the same machine, to a...
2,538,149
2,539,084
What should be contained in a global source code control ignore pattern for Visual Studio 2010?
After installing and using Visual Studio 2010, I'm seeing some newer file types (at least with C++ projects ... don't know about the other types) as compared to 2008. e.g. .sdf, .opensdf, which I guess are the replacement for ncb files with Intellisense info stored in SQL Server Compact files? I also notice .log file...
For C++ projects, you should be fine ignoring the following files: *.sdf and *.opensdf (temporary file opened only while .vcxproj/.sln is loaded to Visual Studio IDE) *.suo *.vcxproj.user ipch folder, if your project uses Pre-compiled Headers (PCH); it is a storage for Intellisense compiler which can now utilise PCH f...
2,538,491
2,538,516
this pointer to base class constructor?
I want to implement a derived class that should also implement an interface, that have a function that the base class can call. The following gives a warning as it is not safe to pass a this pointer to the base class constructor: struct IInterface { void FuncToCall() = 0; }; struct Base { Base(IInterface* inte...
You shold not publish this from the constructor, as your object is not yet initialized properly at that point. In this actual situation, though, it seems to be safe, since you are publishing it only to the base class, which only stores it and does not invoke it until some point later, by which time the construction wil...
2,538,562
2,538,627
In what order does evaluation of post-increment operator happen?
Given std::vector<CMyClass> objects; CMyClass list[MAX_OBJECT_COUNT]; Is it wise to do this? for(unsigned int i = 0; i < objects.size(); list[i] = objects.at(i++)); Or should I expand my loop to this? for(unsigned int i = 0; i < objects.size(); i++) { list[i] = objects.at(i); }
The former is undefined behavior. It's not specified whether list[i] is evaluated (to provide an lvalue for the lhs of the assignment) before or after the function call to objects.at. Hence there is a legal ordering of the various parts of the expression, in which i is accessed (in list[i]) and separately modified (in ...