C++: Calling a constructor to a temporary object

后端 未结 3 1135
天涯浪人
天涯浪人 2021-01-19 17:17

Suppose I have the following:

int main() {
    SomeClass();
    return 0;
}

Without optimization, the SomeClass() constructor will be calle

3条回答
  •  清酒与你
    2021-01-19 17:41

    However, according to an IRC channel that constructor/destructor call may be optimized away if the compiler thinks there's no side effect to the SomeClass constructors/destructors.

    The bolded part is wrong. That should be: knows there is no observable behaviour

    E.g. from § 1.9 of the latest standard (there are more relevant quotes):

    A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input. However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).

    As a matter of fact, this whole mechanism underpins the sinlge most ubiquitous C++ language idiom: Resource Acquisition Is Initialization

    Backgrounder

    Having the compiler optimize away the trivial case-constructors is extremely helpful. It is what allows iterators to compile down to exactly the same performance code as using raw pointer/indexers.

    It is also what allows a function object to compile down to the exact same code as inlining the function body.

    It is what makes C++11 lambdas perfectly optimal for simple use cases:

    factorial = std::accumulate(begin, end, [] (int a,int b) { return a*b; });
    

    The lambda compiles down to a functor object similar to

    struct lambda_1
    {
         int operator()(int a, int b) const 
         { return a*b; }
    };
    

    The compiler sees that the constructor/destructor can be elided and the function body get's inlined. The end result is optimal 1


    More (un)observable behaviour

    The standard contains a very entertaining example to the contrary, to spark your imagination.

    § 20.7.2.2.3

    [ Note: The use count updates caused by the temporary object construction and destruction are not observable side effects, so the implementation may meet the effects (and the implied guarantees) via different means, without creating a temporary. In particular, in the example:

    shared_ptr p(new int);
    shared_ptr q(p);
    p = p;
    q = p;
    

    both assignments may be no-ops. —end note ]

    IOW: Don't underestimate the power of optimizing compilers. This in no way means that language guarantees are to be thrown out of the window!

    1 Though there could be faster algorithms to get a factorial, depending on the problem domain :)

提交回复
热议问题