It was an r-value experiment, but it mutated when gcc whined me about the lack of a move constructor (I deleted it) and did not return to the copy constructor (as I expected) Then I removed -std = C ++ 11 from the flags and tried what you see below, it has a lot of output (initially it wasnβt), because I'm trying to understand why this is not working (I know how to debug, but I find messages on stdout a good indicator of what is happening)
Here is my code:
#include <iostream> class Object { public: Object() { id=nextId; std::cout << "Creating object: "<<id<<"\n"; nextId++; } Object(const Object& from) { id=nextId; std::cout << "Creating object: "<<id<<"\n"; nextId++; std::cout<<"(Object: "<<id<<" created from Object: "<<from.id<<")\n"; } Object& operator=(const Object& from) { std::cout<<"Assigning to "<<id<<" from "<<from.id<<"\n"; return *this; } ~Object() { std::cout<<"Deconstructing object: "<<id<<"\n";} private: static int nextId; int id; }; int Object::nextId = 0; Object test(); int main(int,char**) { Object a; std::cout<<"A ought to exist\n"; Object b(test()); std::cout<<"B ought to exist\n"; Object c = test(); std::cout<<"C ought to exist\n"; return 0; } Object test() { std::cout<<"In test\n"; Object tmp; std::cout<<"Test tmp ought to exist\n"; return tmp; }
Output:
Creating object: 0 A ought to exist In test Creating object: 1 Test tmp ought to exist B ought to exist In test Creating object: 2 Test tmp ought to exist C ought to exist Deconstructing object: 2 Deconstructing object: 1 Deconstructing object: 0
I use deconstruction because deconstruction is already a word, sometimes I use a destructor, I am never happy with a word, I stand for a destructor as a noun.
Here is what I expected:
A to be constructed tmp in test to be constructed, a temporary to be created from that tmp, tmp to be destructed(?) that temporary to be the argument to B copy constructor the temporary to be destructed. C default constructor to be used "" with a temporary from `test` C assignment operator to be used the temporary to be destructed c,b,a to be destructed.
I was called "die-hard C", and I'm trying to learn how to use C ++ as something more than "C with namespaces."
Some might say that "the compiler optimizes it." I would like this person to never answer a question with such an answer now or ever, optimization should not change the state of the program, it should all happen as the specification says, so the compiler can laugh at me by placing a message on cout, which includes a number, he may not even bother to increase the number, etc., but the output of the program will be the same as if he did everything that describes the code.
So this is not optimization, what's going on?