class my_class
{
    ...
    my_class(my_class const &) = delete;
    ...
};

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

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


当前回答

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

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;
}

快乐吗?

我仍然需要做一个更彻底的例子,并运行它来显示一些用法和输出,以及它们对应的错误消息。

另请参阅

https://www.stroustrup.com/C++11FAQ.html#default - section“默认值控制:默认和删除”

其他回答

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

“禁止复制”这句俗语现在可以表达出来了 直接: 类X { / /…… X& operator=(const X&) = delete;//禁止复制 X(const X&) = delete; };

[…] “删除”机制可用于任何功能。例如,我们 可以像这样消除不希望的转换: 结构Z { / /…… Z(很久);//可以初始化一个long long Z(long) = delete;//但不能少 };

= delete是c++ 11中引入的一个特性。由于per =delete,它将不允许调用该函数。

在细节。

假设在一个类中。

Class ABC{
 Int d;
 Public:
  ABC& operator= (const ABC& obj) =delete
  {

  }
};

当调用这个函数进行obj赋值时,它将不被允许。表示赋值操作符将限制从一个对象复制到另一个对象。

这是c++ 0x标准中的新功能,可以删除继承的函数。

= 0表示函数是纯虚函数,不能从该类实例化对象。您需要从中派生并实现此方法 = delete意味着编译器不会为你生成这些构造函数。AFAIK,这只允许在复制构造函数和赋值操作符上。但我不太擅长即将到来的标准。

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

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;
}

快乐吗?

我仍然需要做一个更彻底的例子,并运行它来显示一些用法和输出,以及它们对应的错误消息。

另请参阅

https://www.stroustrup.com/C++11FAQ.html#default - section“默认值控制:默认和删除”