C++ unexpected behaviour (where are my temporaries!?)
This was an r-value experiment but it mutated when gcc whined to me about
lack of move-constructor (I'd deleted it) and didn't fall-back to the copy
constructor (as I expected) I then removed -std=c++11 from the flags and
tried what you see below, it has a lot of output (it didn't initially)
because I am trying to work out why exactly it doesn't work (I know how to
debug but I find messages on stdout to be a good indicator of something
happening)
Here's 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's tmp ought to exist\n";
return tmp;
}
Output:
Creating object: 0
A ought to exist
In test
Creating object: 1
Test's tmp ought to exist
B ought to exist
In test
Creating object: 2
Test's tmp ought to exist
C ought to exist
Deconstructing object: 2
Deconstructing object: 1
Deconstructing object: 0
I use deconstructing, because deconstruction is already a word, sometimes
I use destructor, I'm never quite happy with the word, I favour destructor
as the noun.
Here's 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's copy constructor
the temporary to be destructed.
C's default constructor to be used
"" with a temporary from `test`
C's assignment operator to be used
the temporary to be destructed
c,b,a to be destructed.
I have been called "die-hard C" and I am trying to learn to use C++ as
more than "C with namespaces".
Someone might say "the compiler optimises it out" I'd like that person
never to answer a question with such an answer now or ever, optimisations
must not alter the program state, it must be as if everything happened as
the specification says, so the compiler may humor me by putting a message
on cout that includes the number, it may not bother to even increase the
number and such, but the output of the program would be the same as if it
did do everything the code describes.
So it's not optimisations, what's going on?
No comments:
Post a Comment