views:

127

answers:

2

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.

+9  A: 

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

rlbond
I might suggest using `shared_ptr` or something like if your ownership semantics will not include cycles and are also non-trivial.
Omnifarious
Agreed. The lifetime management here is the tricky part.
Zan Lynx
Using a `shared_ptr` for `this` is not trivial.
Ken Bloom
@Ken: Introducing boost is maybe not trivial, but using `shared_ptr` for `this` is. You add this `: enable_shared_from_this` after `class B`. And then you use `shared_from_this()`
Brian R. Bondy
@Omnifarious: Using a shared pointer in the vector here is a non starter. There is no way of the B class knowing if it is dynamically or statically allocated so there is no concept of ownership (thus it may be better to pass a reference to indicate this (though A would still store a pointer)). B passes to a pointer to itself it is not passing ownership only a reference to himself so that A can keep track of the B's that have been registered using foo().
Martin York
@Brian: lately, I think about `shared_ptr` as being a `std::tr1::shared_ptr`, and AFAIK, there's now equivalent to `enable_shared_from_this` for the `std::tr1::shared_ptr`. Even so, you can't used `shared_from_this` in your constructor.
Ken Bloom
+2  A: 

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.

Brian R. Bondy