我有以下代碼:C++:性病:: TR1 :: shared_ptr的從這個
#include <memory>
class Foo;
typedef std::tr1::shared_ptr<Foo> pFoo_t;
class DoSomething
{
public:
static void doSomething(pFoo_t p) { printf("doing something...\n"); }
static void doSomethingElse(pFoo_t p) { printf("doing something else...\n"); }
};
class Foo
{
public:
Foo() { printf("foo()\n"); }
~Foo() { printf("~foo()\n"); }
public:
void doSomething() { DoSomething::doSomething(pFoo_t(this)); }
void doSomethingElse() { DoSomething::doSomethingElse(pFoo_t(this)); }
};
int _tmain(int argc, _TCHAR* argv[])
{
Foo foo;
foo.doSomething();
foo.doSomethingElse();
return 0;
}
我開始這個樣品,我得到下一個斷言:_BLOCK_TYPE_IS_VALID(pHead-> nBloakUse)。
我該如何避免這種情況?
我用下面的代碼爲解決此問題:
class Foo;
typedef std::tr1::shared_ptr<Foo> pFoo_t;
class DoSomething
{
public:
static void doSomething(pFoo_t p) { printf("doing something...\n"); }
static void doSomethingElse(pFoo_t p) { printf("doing something else...\n"); }
};
class Foo
{
public:
void Init(pFoo_t _pFoo) { m_pFoo = _pFoo; }
Foo() { printf("foo()\n"); }
~Foo() { printf("~foo()\n"); }
public:
void doSomething() { DoSomething::doSomething(m_pFoo.lock()); }
void doSomethingElse() { DoSomething::doSomethingElse(m_pFoo.lock()); }
private:
std::tr1::weak_ptr<Foo> m_pFoo;
};
int _tmain(int argc, _TCHAR* argv[])
{
{
Foo * foo = new Foo();
pFoo_t pFoo(foo);
foo->Init(pFoo);
foo->doSomething();
foo->doSomethingElse();
}
return 0;
}
但我認爲這是一個更好的解決方案。