gpt4 book ai didi

c++ - 在没有 move 构造函数的情况下 move 对象

转载 作者:太空狗 更新时间:2023-10-29 19:40:18 29 4
gpt4 key购买 nike

再说一遍,相关问题没有回答我的问题。

标准很明确:

12.8 Copying and moving class objects,
§9
If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if
— X does not have a user-declared copy constructor,
— X does not have a user-declared copy assignment operator,
— X does not have a user-declared move assignment operator,
— X does not have a user-declared destructor, and
— the move constructor would not be implicitly defined as deleted.
[ Note: When the move constructor is not implicitly declared or explicitly supplied, expressions that otherwise would have invoked the move constructor may instead invoke a copy constructor. — end note ]

因此,在注意到末尾的“注释”之前,我预计这段代码会编译失败(尽管我知道, move 应该回退到复制):

#include <iostream>
using std::cout;
class c
{
public:
c() { cout << "c::c()\n"; }
c( std::initializer_list< int > ) { cout << "c::c( std::initializer_list )\n"; };

c( const c& ) { cout << "c::c( const c& )\n"; }
c& operator=( const c& ) { cout << "c& c::operator=( const c& )\n"; return *this; }

~c() { cout << "c::~c()\n"; }

void f() {}
};

void f( c&& cr ) { cout << "f()\n"; cr.f(); }

int main()
{
c x;
f( std::move( x ) );

return 0;
}

然后看到最后的注释,还是很惊讶,上面的代码输出:

c::c()
f()
c::~c()

注意“缺失的”c::c( const c& )。然后我添加了

c( c&& ) = delete;
c& operator=( c&& ) = delete;

结果还是一样。

我在这里错过了什么?


$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609

编译器标志:-s -O0 -march=native -pthread -std=c++11 -Wall -Wextra -DNDEBUG

最佳答案

您没有 move 任何对象。

std::move 实际上很困惑,因为它没有 move 任何东西。只有 move 构造函数或 move 赋值运算符可以 move 对象,std::move 所做的只是将左值引用 (&) 转换为右值-引用(&&)。

move 构造函数或 move 赋值运算符可以绑定(bind)到右值引用(&&) 并窃取对象内容。

关于c++ - 在没有 move 构造函数的情况下 move 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41099950/

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