1
這段代碼有什麼問題,我該如何解決它?爲什麼這個顯式的析構函數會導致共享ptr中的內存損壞?
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <vector>
struct CTest
{
CTest()
{ std::cout << "ctor CTest" <<std::endl; }
~CTest()
{ std::cout << "dtor CTest" <<std::endl; }
};
struct CSlot
{
CSlot() : m_test(new CTest()), m_num(123)
{ }
~CSlot()
{
// m_test.reset(); // this line fixed the code but I don't know why
m_num = -1;
}
boost::shared_ptr<CTest> m_test;
int m_num;
};
int main()
{
std::vector<CSlot> testVector(1);
std::cout << "1" << std::endl;
new (&testVector[0]) CSlot();
// clear slot
testVector[0].~CSlot();
std::cout << "2" << std::endl;
}
這個代碼看起來像工作,並打印:
ctor CTest
1
ctor CTest
dtor CTest
2
但有時程序崩潰和的valgrind總是說:
==13372== Invalid read of size 4
==13372== at 0x400D8F: boost::detail::atomic_exchange_and_add(int*, int)
...
我可以修復與m_test.reset這種行爲()線,但我認爲有一個更正確的解決方案...
我想創建一些插槽的默認值,後來初始化放置新和有時重置與顯式析構函數......也許我需要一個其他構造函數爲shared_ptr – 2011-12-29 10:17:26
「如果你想使用placement new並調用析構函數直接,你應該把它寫入一個空的字符緩衝區。「不完全是。您必須使用正確對齊的原始內存。但是,如果確保它正確對齊,字符緩衝區就可以。 – 2011-12-29 10:18:14
@SergeDundich:我試圖保持簡單,而char []是最常見的方法。 ;) – jalf 2011-12-29 10:19:22