我目前正在尝试学习如何使用智能指针.然而,在做一些实验时,我发现了以下情况,我无法找到一个令人满意的解决方案:
想象一下,你有一个A类的对象是B类对象(孩子)的父对象,但两者都应该互相认识:
class A;
class B;
class A
{
public:
void addChild(std::shared_ptr<B> child)
{
children->push_back(child);
// How to do pass the pointer correctly?
// child->setParent(this); // wrong
// ^^^^
}
private:
std::list<std::shared_ptr<B>> children;
};
class B
{
public:
setParent(std::shared_ptr<A> parent)
{
this->parent = parent;
};
private:
std::shared_ptr<A> parent;
};
Run Code Online (Sandbox Code Playgroud)
问题是A类的一个对象如何std::shared_ptr将自身(this)传递给它的孩子?
有Boost共享指针(Get a boost::shared_ptrforthis)的解决方案,但是如何使用std::智能指针处理这个问题?
当我运行我的程序时,一切都很顺利.最后打印出来:
*** glibc detected *** ./streamShare: double free or corruption (fasttop): 0x08292130 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xcc2ff1]
/lib/tls/i686/cmov/libc.so.6[0xcc46f2]
/lib/tls/i686/cmov/libc.so.6(cfree+0x6d)[0xcc779d]
/usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0x1c86f1]
./streamShare[0x804be7f]
./streamShare[0x804be3e]
./streamShare[0x804abc0]
./streamShare[0x804a5f2]
./streamShare[0x804a1c4]
./streamShare[0x804a1d7]
./streamShare[0x804a46a]
./streamShare[0x804ba45]
./streamShare[0x804b49c]
./streamShare[0x804ac68]
./streamShare[0x804ac48]
./streamShare[0x804a676]
./streamShare[0x804a237]
./streamShare[0x8049a3f]
./streamShare[0x804d2e5]
./streamShare[0x804d34d]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0xc6eb56]
./streamShare[0x8049361]
Run Code Online (Sandbox Code Playgroud)
我检查过,它发生在一个函数返回时,程序的所有对象都会自动进行实例化.无论如何,我没有为这些对象定义任何析构函数,我尝试使用STL容器和TR1 shared_ptr.我想一切都发生在默认的析构函数中.有没有办法知道它在哪里分手?我的意思是,我想知道哪个物体破坏会造成整个混乱.我正在使用这些容器和共享指针:
typedef std::tr1::shared_ptr<messageListener> mlsptr;
typedef std::map<const char*, mlsptr, ltstr> CONSTCHP2MSLST;
Run Code Online (Sandbox Code Playgroud)
messageListener没有析构函数.其中两个向量:
std::vector<MSG> queueto1;
Run Code Online (Sandbox Code Playgroud)
其中MSG析构函数是:
MSG::~MSG() {
destroy();
}
void MSG::destroy() {
if (payload != NULL)
delete[] payload;
payload = NULL;
payloadLen = 0;
}
Run Code Online (Sandbox Code Playgroud)
从来没有出现问题,我不应该......
任何推荐如何跟踪这个问题?我很笨...
编辑:
这里是VALGRIND输出:
valgrind ./streamShare -v …Run Code Online (Sandbox Code Playgroud)