gpt4 book ai didi

c++ - 即使定义了析构函数也进行移动操作

转载 作者:行者123 更新时间:2023-12-03 07:54:21 27 4
gpt4 key购买 nike

我读到了这个:

N3337 [class.copy]/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, andthe move constructor would not be implicitly defined as deleted.Declaring the destructor and defining it as default counts as user-declared.

这里:Does a default virtual destructor prevent compiler-generated move operations?

但是,这段代码:

struct A1 { virtual ~A1() {};  };

struct B1 : public A1 {
~B1() override {}; };

struct A2 { virtual ~A2() = default; };

struct B2 : public A2 {
~B2() override = default; };

struct A_NO_VIRTUAL {
~A_NO_VIRTUAL() {}; };

struct B_NO_VIRTUAL : public A_NO_VIRTUAL {
~B_NO_VIRTUAL() {}; };


int main() { std::cout << std::is_nothrow_move_constructible_v<B1> << std::is_nothrow_move_constructible_v<B2> << std::is_nothrow_move_constructible_v<B_NO_VIRTUAL> << std::endl; }

打印:111

参见:http://coliru.stacked-crooked.com/a/5c53057a1a4ce3f4

预计:000

这是为什么?

最佳答案

is_move_constructible 粗略检查 MyClass x(std::move(y)); 是否有效。如果 MyClass 没有移动构造函数,但有一个复制构造函数,它将被默默地用来代替移动构造函数,则它可能是有效的。

声明析构函数仅删除移动操作,但保留复制操作(后者已弃用)。

要正确测试这一点,请将成员变量添加到您的类中,并记录对成员的复制和移动构造函数的调用。

关于c++ - 即使定义了析构函数也进行移动操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76426798/

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