Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of this pointer

Tags:

c++

class

this

stl

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.

like image 430
Umbungu Avatar asked Dec 23 '22 01:12

Umbungu


2 Answers

No, there's nothing wrong with that, as long as you are careful about ownership and deletion.

like image 169
rlbond Avatar answered Jan 01 '23 19:01

rlbond


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.

like image 35
Brian R. Bondy Avatar answered Jan 01 '23 20:01

Brian R. Bondy