What is wrong with this code and how can I fix it?
#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;
}
this code looks like working, and prints:
ctor CTest
1
ctor CTest
dtor CTest
2
but sometimes the program crash and valgrind always says:
==13372== Invalid read of size 4
==13372== at 0x400D8F: boost::detail::atomic_exchange_and_add(int*, int)
...
I can fix this behavior with the m_test.reset() line, but I think there is a more correct solution...