MyClass obj = MyClass (); "MyClass ()" refers to a temporary object here?

Consideration of the case when copying is not applied (pre C ++ 17).

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

Temporary objects are created in the following situations:

  • prvalue link binding
  • returns value from function
  • which creates prvalue
  • lambda expression
  • copy requiring initializer conversion
  • list-initialization, which builds std :: initializer_list
  • initialization reference to another, but convertible type or to a bit.

All cases, except the first, seem insignificant, the first, apparently, means a link to a link in the C ++ style ( int &&x = 5; BTW. I do not understand in this case the statement that temporary files are destroyed at the end of a fully functional file, expression ..., object 5 refers to, it seems, is not destroyed at the end of the instruction).

So, as I understand it, the concept of a temporary object includes only those who are guaranteed to be stored (which does not correspond to my situation due to a possible exception). I'm right? Or what am I misunderstanding here?

By the way, is there any difference between MyClass() and 4 in int x = 4; (or 2 + 2 in int x = 2 + 2; )? For example, maybe I'm wrong, and the first one refers to a temporary object, and the other two do not ...

+7
c ++ c ++ 14 temporary
source share
1 answer

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

Temporary members of the class type are created in various contexts: linking the reference to prvalue ([...]), returning prvalue ([...]), the transformation that creates prvalue ([...], 5.4), throwing an exception ([ ...]), and in some initializations ([...]).

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

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

Additionally 8.5 Initializers ([dcl.init]) define the semantics of non-classical type initializers in section (17.8) as

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

whereas for class types, copy constructors are called. Thus, you need a (temporary) object to copy from class types, but not for "other" types.

[1]: actually N4296 , but it should not matter

+1
source share

All Articles