使用此指针

Mew*_*zer 4 c++ stl class this

我有一个关于"this"用法的问题.

假设我有两个A和B类; 他们的粗略轮廓如下:

class A
{
public:
   ...
   void AddB( B* b )
   {
      // inserts B into the vector v
   }

private:
   std::vector<B*> v;
};

class B
{
public:
   ...

   void foo( void )
   {
      ...

      // Adds itself to the queue held in A
      a.AddB( this );
   }  
};
Run Code Online (Sandbox Code Playgroud)

使用"这个"这种方式一般是不好的做法?

谢谢您的帮助.

rlb*_*ond 9

不,这没有什么不妥,只要你小心所有权和删除.

  • @Ken:引入boost可能并不简单,但使用`shared_ptr`来表示`this`是.你在`class B`之后添加`:enable_shared_from_this`.然后你使用`shared_from_this()` (3认同)