c++ - MyClass 对象 = MyClass(); 'MyClass()' 在这里指的是一个临时对象吗?

标签 c++ c++14 temporary

考虑不涉及复制省略的情况(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()4int x = 4;(或 2 + 2int 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/

相关文章:

c++ - 错误 C2664 : 'strcmp' : cannot convert parameter 2 from 'char' to 'const char *'

cuda - 使用 cuda 在设备上进行动态堆栈分配

C++11、C++14、C++17?用什么?

mysql select from table 1 join and order by table 2 优化文件排序

c++ - 我们可以检查目标文件中是否存在 C++ 编译器引入的临时文件吗?

c++ - boost 序列化 - 对不同命名空间中的单一数据类型提供加载和保存方法

c++ - 如何将一个 cpp 包含在另一个 cpp 中,例如复制粘贴而不是声明方式?

c++ - 为什么我可以部分特化但不能完全特化 C++ 中的成员模板?

c++ - 我想我可以理解 N4140 中的 §5.3.4/11,但是扩展的分配函数的概念对我来说是不可理解的

vim - 在 (g)Vim 中隐藏(或折叠)文本列(水平)