#include <iostream>

using namespace std;

struct A
{
    A()
    {
        cout << "A()" << endl;
    }

    ~A()
    {
        cout << "~A()" << endl;
    }

    A(A&&)
    {
        cout << "A(A&&)" << endl;
    }

    A& operator =(A&&)
    {
        cout << "A& operator =(A&&)" << endl;
        return *this;
    }
};

struct B
{
    // According to the C++11, the move ctor/assignment operator
    // should be implicitly declared and defined. The move ctor
    // /assignment operator should implicitly call class A's move
    // ctor/assignment operator to move member a.
    A a;
};

B f()
{
    B b;

    // The compiler knows b is a temporary object, so implicitly
    // defined move ctor/assignment operator of class B should be
    // called here. Which will cause A's move ctor is called.
    return b;
}

int main()
{
    f();
    return 0;
}

我的预期输出应为:
A()
A(A&&)
~A()
~A()

但是,实际输出为:(C++编译器为:Visual Studio 2012)
A()
~A()
~A()

这是VC++的错误吗?还是只是我的误会?

最佳答案

根据this blog post的说法,VC++ 2012当前实现了N2844 + DR1138,但没有实现N3053。因此,编译器不会为您隐式生成 move 构造函数或赋值运算符。如果添加显式默认值并将构造函数移至B,则将获得所需的输出。

07-24 09:45
查看更多