Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ unexpected behaviour (where are my temporaries!?)

Tags:

c++

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?

like image 579
Alec Teal Avatar asked Aug 28 '13 11:08

Alec Teal


3 Answers

It is an optimization, the only one that is allowed to alter observable behaviour of a program.

Here's the paragraph 12.8./31, taken from standard draft n3337 (emphasis mine):

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization. This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

— in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv- unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

— in a throw-expression, when the operand is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object (15.1) can be omitted by constructing the automatic object directly into the exception object

— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

— when the exception-declaration of an exception handler (Clause 15) declares an object of the same type (except for cv-qualification) as the exception object (15.1), the copy/move operation can be omitted by treating the exception-declaration as an alias for the exception object if the meaning of the program will be unchanged except for the execution of constructors and destructors for the object declared by the exception-declaration.

[Example... omitted]

The semantics of a copy/move constructor are just that, copying/moving the contents of an object while initializing another one. If your copy constructors send emails with invitations to your birthday party you should not be surprised if you end up partying alone :)

OK, some copy constructors do other things, too. Think reference counting of a smart pointer. But if that gets optimized away, it's fine. There was no copy and nothing needed to be counted.

like image 173
jrok Avatar answered Nov 09 '22 03:11

jrok


I believe you are experiencing Copy Elision. And thus yes, it is optimizations.

http://en.wikipedia.org/wiki/Copy_elision

In C++ computer programming, copy elision refers to a compiler optimization technique that eliminates unnecessary copying of objects. The C++ language standard generally allows implementations to perform any optimization, provided the resulting program's observable behavior is the same as if, i.e. pretending, the program was executed exactly as mandated by the standard.

The standard also describes a few situations where copying can be eliminated even if this would alter the program's behavior, the most common being the return value optimization.

The emphasis is mine.

like image 29
Kaz Dragon Avatar answered Nov 09 '22 02:11

Kaz Dragon


Since copying/moving temporary objects has a cost, compilers are explicitly allowed to elide temporary objects, even if the corresponding constructors or destructors have side-effects. Copy/move elision is typically not considered an optimization and most compilers elide construction of temporary objects even in debug mode (which is reasonable as you don't want to have different behavior between debug and optimized builds).

The relevant clause in the C++11 standard is 12.8 [class.copy] paragraph 31:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. ...

The cases where copy/move elision is allowed are:

  • in return statements
  • in throw expressions
  • when a temporary is not bound to a reference
  • in the catch clause

The exact rules have a few extra conditions.

like image 3
Dietmar Kühl Avatar answered Nov 09 '22 04:11

Dietmar Kühl