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

Viewed 611

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 MyClass() and 4 in int x = 4; (or 2 + 2 in 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...

2 Answers

Yes, it creates a temporary, because this is an explicit conversion creates a prvalue.

In this context MyClass obj = MyClass();, the MyClass() is prvalue. And from the qoute you're provided, it matches the situation "conversion that creates a prvalue", So yes a temporary is created.

Actually the compiler will convert this line MyClass obj = MyClass(); to: (assuming MyClass has non-deleted default and copy contructors)

MyClass _tmp{};  // (default-constructed)
MyClass obj = _tmp; // (copy-constructed)

The first line calls: MyClass::MyClass(this=&_tmp)

The second line calls: MyClass::MyClass(MyClass const&=tmp, this=&obj)

Related