ledonter ledonter - 1 month ago 7
C++ Question

MyClass obj = MyClass(); Does 'MyClass()' refer to a temporary object here?

Considering the case where no copy-elision is involved (pre C++17).

From cppreference (again, suppose C++14):

Temporary objects are created in the following situations:

  • binding a reference to a prvalue

  • returning a prvalue from a function

  • conversion that creates a prvalue

  • lambda expression

  • copy-initialization that requires conversion of the initializer

  • list-initialization that constructs an std::initializer_list

  • reference-initialization to a different but convertible type or to a bitfield.

All the cases except the first one seem irrelevant, the first one seems to mean C++-style reference binding (
int &&x = 5;
BTW I don't understand in such circumstance the statement that temporaries are destroyed at the end of the full-expression..., the object 5 is referring to doesn't seem to be destroyed at the end of the statement).

So, as I understood, the notion of a temporary object only includes those who are guaranteed to be stored (which is not the case in my situation due to possible elision). Am I correct? Or else what do I misunderstand here?

BTW is there any difference between
int x = 4;
2 + 2
int x = 2 + 2;
)? Like maybe I'm incorrect and the first one DOES refer to a temporary object while the other two do not...

Answer Source

The C++14 standard[1] says in 12.2 regarding Temporary objects ([class.temporary]):

Temporaries of class type are created in various contexts: binding a reference to a prvalue ([...]), returning a prvalue ([...]), a conversion that creates a prvalue ([...], 5.4), throwing an exception ([...]), and in some initializations ([...]).

In MyClass obj = MyClass();, MyClass() is a Explicit type conversion in functional notation, so it is a temporary object because it falls under "conversion that creates a prvalue".

This does not apply for the 4 in int x = 4; because the rule refers to "class types" but int is a "fundamental type".

Additionally 8.5 Initializers ([dcl.init]) defines the semantics of non-class type initializers in clause (17.8) as

Otherwise, the initial value of the object being initialized is the (possibly converted) value of the initializer expression. [...]

while for class types, (copy) constructors are invoked. So you need a (temporary) object to copy from for class types, but not for "other" types.

[1]: actually N4296, but that shouldn't make a difference