[英]Deleted constructor called in initializer
Yes, I know destructors are important but this is a situation where both Foo and Bar are going to be singletons.是的,我知道析构函数很重要,但在这种情况下 Foo 和 Bar 都将成为单例。 And for debugging purposes I want to make sure the singleton object is never deleted (I accidentally made that happen once).出于调试目的,我想确保单例对象永远不会被删除(我不小心做了一次)。
class Bar {
public:
Bar();
~Bar() = delete;
}
class Foo {
public:
Foo();
Bar b;
}
All constructor and destructor bodies are empty.所有构造函数和析构函数体都是空的。 So the cpp just looks like所以 cpp 看起来像
Foo::Foo() {
}
This code causes an error that I do not expect.此代码会导致我不希望出现的错误。 I would understand it to be frustrated about not having a destructor in the destructor method of Foo but instead I get an error on the constructor.我会理解它对在 Foo 的析构函数方法中没有析构函数感到沮丧,但我在构造函数上得到了一个错误。 For some reason the compiler says it is referencing a deleted function.出于某种原因,编译器说它引用了一个已删除的函数。 Why does it care about this in the constructor?为什么它在构造函数中关心这个?
Having Bar b;
有Bar b;
as class member implies that there must be an accessible destructor for b
.因为类成员意味着b
必须有一个可访问的析构函数。
The rationale for this is so that it can be destroyed if an exception is thrown some point during construction of a Foo
, after b
was constructed but before construction of the Foo
was complete.这样做的基本原理是,如果在构造 a Foo
期间,在构造b
之后但在构造Foo
完成之前的某个时刻抛出异常,则可以将其销毁。
Unfortunately, even if your code is such that there is no possible exception, this rule still stands.不幸的是,即使您的代码没有任何可能的例外,这条规则仍然有效。 You will have to redesign your class layout so that singletons are not included directly as data members of other classes, even if they are singletons too.你将不得不重新设计你的类布局,这样单例就不会直接作为其他类的数据成员包含在内,即使它们也是单例。
References:参考:
C++17 [class.base.init]/12: C++17 [class.base.init]/12:
In a non-delegating constructor, the destructor for each potentially constructed subobject of class type is potentially invoked.在非委托构造函数中,可能会调用每个可能构造的类类型子对象的析构函数。 [Note: This provision ensures that destructors can be called for fully-constructed subobjects in case an exception is thrown (18.2). [注意:该条款确保在抛出异常的情况下可以为完全构造的子对象调用析构函数(18.2)。 —end note ] ——尾注]
Also [class.dtor]/12.4:还有 [class.dtor]/12.4:
A program is ill-formed if a destructor that is potentially invoked is deleted or not accessible from the context of the invocation.如果可能调用的析构函数被删除或无法从调用上下文访问,则程序格式错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.