gpt4 book ai didi

c++ - 对类中的方法正确使用 `= delete`

转载 作者:IT老高 更新时间:2023-10-28 12:41:51 25 4
gpt4 key购买 nike

对于取消定义一个类的所有其他生成的方法和构造函数,以下代码段是否正确?

struct Picture {

// 'explicit': no accidental cast from string to Picture
explicit Picture(const string &filename) { /* load image from file */ }

// no accidental construction, i.e. temporaries and the like
Picture() = delete;

// no copy
Picture(const Picture&) = delete;

// no assign
Picture& operator=(const Picture&) = delete;

// no move
Picture(Picture&&) = delete;

// no move-assign
Picture& operator=(Picture&&) = delete; // return type correct?
};

这会删除所有默认编译器实现,只留下析构函数,对吗?如果没有它,我猜这个类将(几乎)无法使用,但我也可以删除它,对吗?

move-assign operator=(Picture&&)的返回类型Picture&是否正确?如果我为返回类型编写 Picture&& 会有所不同吗?

最佳答案

除了Xeo的回答:

是的,一切都是正确的。如果您愿意,您可以消除所有已删除的成员,但已删除的复制构造函数和已删除的复制分配具有相同的效果:

struct Picture {  // Also ok

// 'explicit': no accidental cast from string to Picture
explicit Picture(const string &filename) { /* load image from file */ }

// no copy
Picture(const Picture&) = delete;

// no assign
Picture& operator=(const Picture&) = delete;
};

复制构造函数的显式声明禁止隐式生成默认构造函数、 move 构造函数和 move 赋值成员。明确删除这些成员是个人喜好问题。有些人可能会将其视为很好的文档。其他人可能会认为它过于冗长。

关于c++ - 对类中的方法正确使用 `= delete`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5687055/

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