First time is that the function FirstInteger.Return(FirstInteger) will return an object by value, thus invoking the copy constructor. Second time is that we use an object to directly initialise another object which is "SecondInteger".
I understand that the following code requires a move constructor to become more efficient. BUT! When I try the following code out, the compiler tells me the following:
As you can see, the copy constructor is only invoked once, and that's what drives me crazy. Is it because I am using the Microsoft Visual Studio Express 2013, and it has some optimisation that behaves like a move constructor? I understand that the following codes are quite long, but can someone help me with this please?
Your code fails to compile on my machine because of the following:
1 2 3
MyInteger(int Input)
{
if(Input != NULL)
main.cpp|13|error: NULL used in arithmetic [-Werror=pointer-arith]|
First if your compiler supports C++11 you should be using nullptr instead of NULL. Second you shouldn't be trying to compare an int to NULL (or nullptr). NULL (or nullptr) should only be used in connection to pointers.
Why do you think the copy constructor should be called more than once?
The 'FirstInteger.Return(FirstInteger)' will return an object by value, thus invoking a copy constructor.
The 'MyInteger SecondInteger(An object returned by the above function )' will also invoke a copy constructor since we are using an object to initialise another object.
In your case, compilers are expected (and as of C++17 required) to only call the copy constructor once in your code. That copy constructor creates main::SecondInteger using Return::Input (which aliases main::FirstInteger) as its argument.