cat*_*dle 0 c++ visual-studio c++11 visual-studio-2013
在下面的代码中,创建nested对象的行仅打印带有gcc的 "constructor" ,但不打印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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
constructor
copy constructor
destructor
destructor
Run Code Online (Sandbox Code Playgroud)
所以我猜这里发生的事情是临时对象被复制进去n.没有编译器生成的移动构造函数,所以这就是为什么它不是一个移动.
我想知道这是一个错误还是可接受的行为?为什么添加默认构造函数会阻止复制?
这不是auto问题所在; 以下内容将展示相同:
nested n = nested{};
Run Code Online (Sandbox Code Playgroud)
临时用直接初始化{},然后用n它复制初始化,因为test是一个类类型(在这种情况下,有用户定义的构造函数).
一个实现允许直接初始化最终目标(n),但没有义务来,所以无论是合法的.
标准的8.5和8.5.1中有很多(实际上很多)细节.
| 归档时间: |
|
| 查看次数: |
173 次 |
| 最近记录: |