gpt4 book ai didi

c++ - 是否存在删除了 ctor 的类有用的情况?

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:46 25 4
gpt4 key购买 nike

我想知道为什么标准允许这种声明。

class A
{
public:
A() : bar(0){}
A(int foo) : bar(foo){}
private:
int bar;
};

class B : public A
{
public:
B() = delete;
};

B 无法实例化。

  B b1; //error: use of deleted function ‘B::B()’
B b2(2); //error: no matching function for call to ‘B::B(int)’

仍然如此

class A
{
public:
A() : bar(0){}
private:
int bar;
};

class B : public A
{
public:
B() = delete;
};

给出

B b1; //error: use of deleted function ‘B::B()’

注意:这与没有默认构造函数不同:

class G
{
protected:
int assign;
};

class H : public G
{
public:
H() = delete;
};

给予

G g1; //works
//H h1; -- error: use of deleted function ‘H::H()’

这在任何情况下都有用吗?

最佳答案

Is there any case where a class with deleted ctor could be useful?

可以在不创建实例的情况下使用类。此类的最典型示例是类型特征:例如 std::is_samestd::numeric_limits 的所有功能都可以在不创建实例的情况下使用。因此,可以删除它们的构造函数而不会丢失任何功能。

也就是说,通常没有必要删除此类类的构造函数,事实上,标准类型特征的隐式构造函数不会被删除。构造函数的删除通常用于仅删除某些构造函数,而不是所有构造函数。需要明确的是:仅仅因为某些东西不典型,并不意味着它应该是一个错误。

关于c++ - 是否存在删除了 ctor 的类有用的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257532/

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