对象销毁和委托构造函数
根据关于委托构造函数的这个问题,当第一个构造函数完成时,将调用析构函数。
这与以下代码一致:
struct test {
test() { std::cout << "default constr\n"; }
test(int) : test() { std::cout << "argument constr\n"; throw int{}; }
~test() { std::cout << "destr\n"; }
};
int main()
{
try {
test t{3};
} catch(...)
{
std::cout << "caught\n";
}
}
输出:
default constr
argument constr
destr
caught
但是,Stroustrup 在他的书中(第 4 版,第 503 页)说了以下内容:
在其构造函数完成之前,对象不会被视为已构造 (...)。当使用 委托构造函数,在委托构造函数完成之前,该对象不被视为已构造 完成——仅完成委托构造函数是不够的。析构函数不会 调用一个对象,除非它的原始构造函数完成。
是我误读了还是他有别的意思?
According to this question about delegating constructors, a destructor is called when the first constructor has finished.
This is consistent with the following code:
struct test {
test() { std::cout << "default constr\n"; }
test(int) : test() { std::cout << "argument constr\n"; throw int{}; }
~test() { std::cout << "destr\n"; }
};
int main()
{
try {
test t{3};
} catch(...)
{
std::cout << "caught\n";
}
}
output:
default constr
argument constr
destr
caught
But, Stroustrup says the following in his book (4th edition, page 503):
An object is not considered constructed until its constructor completes (...). When using a
delegating constructor, the object is not considered constructed until the delegating constructor
completes – just completing the delegated-to constructor is not sufficient. A destructor will not be
called for an object unless its original constructor completed.
Am I misreading this or does he mean something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不这么认为。
我不这么认为。
据我所知,这似乎是书中的一个错误。本书的描述可能基于原始的委托构造函数 提案。该行为在提案的后续修订中发生了变化。
I don't think so.
I don't think so.
This seems to be an error in the book as far as I can tell. The book's description may be based on the original delegating constructors proposal. The behaviour was changed in following revisions of the proposal.