gpt4 book ai didi

c++ - 了解默认 move 构造函数定义

转载 作者:行者123 更新时间:2023-11-30 00:50:04 26 4
gpt4 key购买 nike

在阅读 move constructor 时来自当前 standard ,我可以看到以下内容:

12.8 Copying and moving class objects

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, and
— X does not have a user-declared destructor.

[ 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>
struct handleclass {
public:
handleclass():length{0}, p{nullptr} {}
handleclass(size_t l):length{l},p{new int[length]} { }
~handleclass() { delete[] p; }
size_t length;
int* p;
};

handleclass function(void) {
handleclass x(10);
return x;
}

int main() {
handleclass y;
std::cout<<y.length<<std::endl;
y = function();
std::cout<<y.length<<std::endl;

handleclass a;
handleclass b(10);
a = std::move(b);

return 0;
}

显然,这个程序是不正确的,并且由于两个对象对资源的浅拷贝,会产生未定义的行为(终止)。但我的重点是了解程序中生成和使用的默认 move 构造函数。我希望这个例子有意义。

在上面的程序中,在应该调用 move 构造函数的两种情况下,在我看来编译器正在使用默认的复制构造函数。

根据标准中提到的上述规则,我认为我们应该得到编译器错误,因为现在程序显式地尝试调用 move 构造函数,并且用户既没有实现也没有编译器生成默认值(隐式),因为上面的规则不满足? .

然而,这是在没有任何警告/错误的情况下编译并成功运行的。有人可以解释一下默认(隐式) move 构造函数的概念吗?或者我遗漏了什么?

最佳答案

你忘了 copy elision这意味着 y = function(); 实际上可能不会调用任何复制或 move 构造函数;只是 x 的构造函数和赋值运算符。

某些编译器允许您禁用复制省略,如该线程中所述。

我不确定“在两种情况下都应调用 move 构造函数”是什么意思。实际上,应该调用 move 构造函数的情况为零(您的对象没有 move 构造函数),在一种情况下可以调用复制构造函数(return 语句)但可能会被省略。

您有两种赋值运算符:y = function();a = std::move(b);。同样,由于您的类没有 move 赋值运算符,因此它们将使用复制赋值运算符。

如果您从复制构造函数和 move 构造函数中将代码添加到您的对象到 cout,这可能会有助于您的测试。

关于c++ - 了解默认 move 构造函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227431/

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