繁体   English   中英

在使用auto时初始化struct会在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 没有编译器生成的move构造函数,所以这就是为什么它不是move的原因。

我想知道这是错误还是可接受的行为? 为什么添加默认构造函数会在此处阻止复制?

问题不是auto ,而是auto 以下将显示相同的内容:

nested n = nested{};

临时用{}进行直接初始化,然后n其进行副本初始化,因为test是一个类类型(在这种情况下,具有用户定义的构造函数)。

允许实现直接初始化最终目标( n ),但不必强制执行,因此两者都是合法的。

标准8.5和8.5.1中的很多(实际上是很多 )细节。

这是MSVC无法进行复制省略的原因(我想这与brace-init-constructor有关)。 两种方式都是完全合法的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM