gpt4 book ai didi

c++ - 为什么 C++11 的 move 构造函数/赋值运算符不按预期运行

转载 作者:可可西里 更新时间:2023-11-01 17:05:44 25 4
gpt4 key购买 nike

#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 构造函数或赋值运算符。如果您添加显式默认值并将构造函数 move 到 B,那么您将获得您期望的输出。

关于c++ - 为什么 C++11 的 move 构造函数/赋值运算符不按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com