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.
No, there's nothing wrong with that, as long as you are careful about ownership and deletion.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With