Destructor Gotcha(Delegating Constructors in C++11)解决思路
Destructor Gotcha(Delegating Constructors in C++11)
问题来源:http://741mhz.com/delegating-constructors/
运行环境:VS2013 ,Win7 64bit, 中文
作者有一段话:
As a result, such a faulty program would try to delete an instance of P2 object twice (and runtime would hopefully abort the program):
问题1:我不明白的是为什么是twice??
问题2: 我把作者的例子放进VS2013里运行,结果却有不同!!为什么
int main() {
try {
A a2(7.5, std::unique_ptr<P2>(new P2));
} catch(const std::exception&) {
}
}
我在运行到
~A() {
std::cout << "A::~A()" << std::endl;
delete p;
}
输出了
A::~A()
P::~P()
然后弹出窗口提示触发断点
"HEAP[MFCSolution.exe]: Invalid address specified to RtlValidateHeap( 00F50000, 00F9615C )
MFCSolution.exe 已触发了一个断点。"
我可以看到断点停在了afxmem.cpp里的
if defined(_DEBUG)
_free_dbg(p, _NORMAL_BLOCK); //指向这里!!停住了
但作者输出的是
A::~A()
P2::~P2()
P1::~P1()
P1::~P1()
------解决方案--------------------
1. 因为 ~A 和 ~unique_ptr 都会试图 delete 同一个对象。
2. 所以作者说:This, however, would trigger undefined behavior。UB 没有一定的表现形式,否则就不用叫未定义行为了。
ps. 引贴中的例子是为了表现问题而故意写的烂程序,楼主还是多看点儿权威的好书吧。
问题来源:http://741mhz.com/delegating-constructors/
运行环境:VS2013 ,Win7 64bit, 中文
作者有一段话:
As a result, such a faulty program would try to delete an instance of P2 object twice (and runtime would hopefully abort the program):
问题1:我不明白的是为什么是twice??
问题2: 我把作者的例子放进VS2013里运行,结果却有不同!!为什么
int main() {
try {
A a2(7.5, std::unique_ptr<P2>(new P2));
} catch(const std::exception&) {
}
}
我在运行到
~A() {
std::cout << "A::~A()" << std::endl;
delete p;
}
输出了
A::~A()
P::~P()
然后弹出窗口提示触发断点
"HEAP[MFCSolution.exe]: Invalid address specified to RtlValidateHeap( 00F50000, 00F9615C )
MFCSolution.exe 已触发了一个断点。"
我可以看到断点停在了afxmem.cpp里的
if defined(_DEBUG)
_free_dbg(p, _NORMAL_BLOCK); //指向这里!!停住了
但作者输出的是
A::~A()
P2::~P2()
P1::~P1()
P1::~P1()
------解决方案--------------------
1. 因为 ~A 和 ~unique_ptr 都会试图 delete 同一个对象。
2. 所以作者说:This, however, would trigger undefined behavior。UB 没有一定的表现形式,否则就不用叫未定义行为了。
ps. 引贴中的例子是为了表现问题而故意写的烂程序,楼主还是多看点儿权威的好书吧。