对象销毁和委派构造函数
object destruction & delegating constructor
根据this question关于委派构造函数的说法,当第一个构造函数完成时调用析构函数。
这与下面的代码是一致的:
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 页)中说了以下内容:
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?
我不这么认为。
据我所知,这似乎是书中的一个错误。本书的描述可能基于原始委托构造函数 proposal。在提案的后续修订中更改了行为。
根据this question关于委派构造函数的说法,当第一个构造函数完成时调用析构函数。
这与下面的代码是一致的:
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 页)中说了以下内容:
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?
我不这么认为。
据我所知,这似乎是书中的一个错误。本书的描述可能基于原始委托构造函数 proposal。在提案的后续修订中更改了行为。