简体   繁体   中英

Usage of this pointer

I have a question relating to the usage of "this".

Suppose I have two classes A & B; their rough outline is as follows:

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 );
   }  
};

Is using "this" in this way generally bad practice?

Thank you for your help.

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

If you can introduce boost, it's better practice to use boost::shared_ptr instead of direct pointers, because you will eliminate the need to manually free the memory in the right order. And you will eliminate the chance of having dangling pointers that point to already freed memory.

Then you can use shared_from_this() instead of this . It will create a shared pointer instead of a direct pointer for your type. Your type B would derive from enable_shared_from_this .

Your type A would hold a vector of boost::shared_ptr<B> instead of direct pointers.

Here's an example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM