= 函数声明后删除的含义

新手上路,请多包涵
class my_class
{
    ...
    my_class(my_class const &) = delete;
    ...
};

= delete 在这种情况下是什么意思?

是否有任何其他“修饰符”(除了 = 0= delete )?

原文由 Pat O‘Keefe 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 617
2 个回答

删除函数是 C++11 的一个特性

“禁止复制”的常用成语现在可以直接表达:

 class X {
    // ...
    X& operator=(const X&) = delete;  // Disallow copying
    X(const X&) = delete;
};

[…]

“删除”机制可用于任何功能。例如,我们可以像这样消除不需要的转换:

 struct Z {
    // ...

    Z(long long);     // can initialize with a long long
    Z(long) = delete; // but not anything less
};

原文由 Prasoon Saurav 发布,翻译遵循 CC BY-SA 4.0 许可协议

一个小例子来总结一些常见的用法:

 class MyClass
{
public:
    // Delete copy constructor:
    // delete the copy constructor so you cannot copy-construct an object
    // of this class from a different object of this class
    MyClass(const MyClass&) = delete;

    // Delete assignment operator:
    // delete the `=` operator (`operator=()` class method) to disable copying
    // an object of this class
    MyClass& operator=(const MyClass&) = delete;

    // Delete constructor with certain types you'd like to
    // disallow:
    // (Arbitrary example) don't allow constructing from an `int` type. Expect
    // `uint64_t` instead.
    MyClass(uint64_t);
    MyClass(int) = delete;

    // "Pure virtual" function:
    // `= 0` makes this is a "pure virtual" method which *must* be overridden
    // by a child class
    uint32_t getVal() = 0;
}

去做:

  1. 我仍然需要做一个更详尽的示例,并运行它以显示一些用法和输出,以及它们相应的错误消息。

也可以看看

  1. https://www.stroustrup.com/C++11FAQ.html#default - 部分“默认值控制: defaultdelete

原文由 Gabriel Staples 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题