gpt4 book ai didi

c++ - 在C++17中移动/复制构造函数/赋值是否为 "deleted"或 "not declared"是否成立?

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

我在看 this answer关于 What are the rules for automatic generation of move operations? ,我希望现在答案已经确定。

幻灯片显示了哪些构造函数/赋值运算符是“未声明的”、“默认的”或“已删除的”,基于已在类中声明的内容,显示:

enter image description here

取自这些 slides ,红色方 block 表示此行为已弃用。

编译时:

#include <iostream>
struct X
{
template<typename...T>
X(T&&...) {
std::cout << "Yay!\n";
}

~X() {}
};

int main() {
X x0;
X x1{x0};
X x2{std::move(x0)};
}

看起来它们已经“未声明”,因为它编译并且输出是“耶!”三遍(这很好,至少对我而言)。但我想确认我可以依赖这种行为。

编辑

已被Frank指出也就是说,如果还添加了复制构造函数,它仍然会说“耶!”三遍,这是一个有趣的行为。做进一步的测试,如果添加移动构造函数,它只会说“耶!”两次。谁能解释这种行为?

最佳答案

根据 N4659(几乎是 C++17 标准),它们仍被定义为默认,但该行为(仍然)已弃用。

If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted. The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.

If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy assignment operator is defined as deleted; otherwise, it is defined as defaulted. The latter case is deprecated if the class has a user-declared copy constructor or a user-declared destructor.

关于c++ - 在C++17中移动/复制构造函数/赋值是否为 "deleted"或 "not declared"是否成立?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100502/

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