我有以下法典:
#include <memory>
class Foo;
typedef std::tr1::shared_ptr<Foo> pFoo_t;
class DoSomething
{
public:
static void doSomething( pFoo_t p) { printf( "doing something...
"); }
static void doSomethingElse( pFoo_t p) { printf( "doing something else...
"); }
};
class Foo
{
public:
Foo() { printf( "foo()
"); }
~Foo() { printf( "~foo()
"); }
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...
"); }
static void doSomethingElse( pFoo_t p) { printf( "doing something else...
"); }
};
class Foo
{
public:
void Init(pFoo_t _pFoo) { m_pFoo = _pFoo; }
Foo() { printf( "foo()
"); }
~Foo() { printf( "~foo()
"); }
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;
}
但我认为有一个更好的解决办法。