C ++ copy constructors
I recently wrote a piece of code that did
SomeClass someObject;
mysqlpp::StoreQueryResult result = someObject.getResult();
where SomeClass :: getResult () looks like this:
mysqlpp::StoreQueryResult SomeClass::getResult()
{
mysqlpp::StoreQueryResult res = ...<something>...;
return res;
}
Now using the example in the first snippet of code, when I compiled and run, the program crashed with an ABORT signal. Then I changed the first snippet to:
SomeClass someObject;
mysqlpp::StoreQueryResult result(someObject.getResult());
which worked fine. Also, just to try it, I changed it back to:
SomeClass someObject;
mysqlpp::StoreQueryResult result;
result = someObject.getResult();
which also worked great.
Now I just can't figure out why the first example failed and the next two succeeded. As I understand it, in the first example, the copy constructor is used to initialize the result. But isn't that the case in the second example? So why did the second example succeed? The third example makes a little more sense - since the const copy is not used, we just assign it after construction.
In short, what's the difference between:
FooClass a = someObject.someMethodReturningFooClassInstance();
and
FooClass a(someObject.someMethodReturningFooClassInstance());?
Thanks Muchos!
source to share
Strictly speaking, in the first case, the default constructor is called, followed by the assignment operator, while in the second case, it only uses the copy constructor.
Ok, my initial guess was wrong and apparently only the copy constructor will be called in both cases (well, in the case of assignment, an additional conversion constructor might also be called). I will run the compiler after some sleep and test this in my development environment.
source to share
You can just put a breakpoint (or even a printf statement) inside the copy constructor and you know exactly when it was called, you know. SO cannot replace basic debugging.;)
But yes, the copy constructor should be called in the first two cases. In the third case, the assignment operator is used instead.
Have you tried running it in the debugger? It must break the ABORT signal.
source to share
In the purest theory, the copy constructor should be called in both cases. However, there is something called Return Value Optimization (RVO) that the compiler can use in these cases. If RVO is used, the copy constructor will not be called. Perhaps your compiler is using RVO in one case and not the other?
Edit: This only applies to case
SomeClass someObject;
mysqlpp::StoreQueryResult result;
result = someObject.getResult();
source to share