考虑不涉及复制省略的情况(C++17 之前)。
来自 cppreference(再次假设 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.
除了第一个之外的所有情况似乎都无关紧要,第一个似乎意味着 C++ 样式的引用绑定(bind)(int &&x = 5;
顺便说一句,在这种情况下我不明白临时文件的声明在完整表达式的末尾被销毁...,对象 5 所指的似乎没有在语句末尾被销毁)。
因此,据我所知,临时对象的概念仅包括那些保证被存储的对象(由于可能省略,在我的情况下不是这种情况)。我对么?否则我在这里误解了什么?
顺便说一句,MyClass()
和 4
在 int x = 4;
(或 2 + 2
在 int x = 2 + 2;
中?就像我可能是不正确的,第一个确实引用了一个临时对象,而其他两个则没有...
最佳答案
C++14 标准[1] 在 12.2 中关于临时对象 ([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 ([...]).
在MyClass obj = MyClass();
中,MyClass()
在函数符号中是一个显式类型转换,所以它是一个临时对象,因为它属于“转换”创建一个纯右值”。
这不适用于 int x = 4;
中的 4
,因为该规则指的是“类类型”,但 int
是一个“基本型”。
另外 8.5 Initializers ([dcl.init]) 将子句 (17.8) 中非类类型初始化器的语义定义为
Otherwise, the initial value of the object being initialized is the (possibly converted) value of the initializer expression. [...]
而对于类类型,(复制)构造函数被调用。所以你需要一个(临时)对象来复制类类型,而不是“其他”类型。
[1]:实际上N4296 , 但这应该没有什么区别
关于c++ - MyClass 对象 = MyClass(); 'MyClass()' 在这里指的是一个临时对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45698374/