在使用auto时初始化结构会导致VS 2013中的副本
initializing struct while using auto causes a copy in VS 2013
在以下代码中,创建nested
对象的行只使用gcc打印"构造函数",而不使用VS 2013打印:
#include <iostream>
using namespace std;
struct test {
test() { cout << "constructor" << endl; }
test(const test&) { cout << "copy constructor" << endl; }
test(test&&) { cout << "move constructor" << endl; }
~test() { cout << "destructor" << endl; }
};
struct nested {
test t;
// nested() {}
};
auto main() -> int {
// prints "constructor", "copy constructor" and "destructor"
auto n = nested{};
cout << endl;
return 0;
}
输出:
constructor
copy constructor
destructor
destructor
所以我想这里发生的是一个临时对象被复制到n
中。没有编译器生成的移动构造函数,所以这就是它不是移动的原因。
我想知道这是一个错误还是一种可以接受的行为?为什么添加默认构造函数会阻止复制?
问题不是auto
;以下将显示相同:
nested n = nested{};
临时用{}
直接初始化,然后用它复制初始化n
,因为test
是一个类类型(在本例中,具有用户定义的构造函数)。
允许直接初始化最终目标(n
),但没有义务,因此两者都是合法的。
本标准8.5和8.5.1中的大量(实际上是大量)详细信息。
这是MSVC执行复制省略的失败(我想这与brace-init构造函数有关)。这两种方式都是完全合法的。
相关文章:
- 构建在VS 2013中找不到平台工具集= 'v141'
- MFC 对话框属性表用法在 VS 2017 中产生错误,适用于 VS 2013
- VS 2013 和 VS 2015 的不同C++可再发行 DLL
- 错误的LNK2005已定义为将C /Fortran解决方案更新为VS 2013
- VS 2013 SFINAE 缺陷的解决方法
- 与openCV的vs 2013中的lib链接
- VS 2013 DirectX Project Vertex着色器文件缺失
- VS 2013 errorC3861 PeekMessage etc and errorC2065 WNDCLASSEX
- 以下代码在 VS 2013 发布/调试中生成不同的结果
- VS 2013 社区 - 创建代码片段
- 如何使Ws2_32.lib与针对Windows 8.1的VS 2013项目协同工作
- VS 2013模板无法编译
- 最好的方法太分开类,VS 2013
- OpenGL未解析的外部符号VS 2013
- 无法在VS 2013、Windows 8.1中创建Win32控制台应用程序
- 禁用CPP中某部分代码的代码分析(VS 2013)
- C++ IDE 从 VS 6 迁移到 VS 2013
- 谷歌测试预构建VS 2013
- 闪电战在 vs 2013 中不起作用
- 使用 C++ 在 directX 11 中的 VS 2013 中获取 LNK 2019 错误