Boost logo

Boost Users :

Subject: Re: [Boost-users] [PtrContainer] Inserting "this" Pointers
From: Binglong Xie (binglongx_at_[hidden])
Date: 2010-09-22 00:25:31


I am not an expert on "this", so my understanding below may not be accurate.

The insertion itself is of course valid:
    class A
    {
        ...
        void insert_me(std::vector<A*>& v) { v.push_back(this); }
    };
However, consider how the client may use it:
    A* aa = ...;
    aa->insert_me(v);
Since you get a hand on aa already, why don't you just call instead:
    v.push_back(aa);

Now if you use smart pointers instead of naked pointers, the latter approach
lets the client code handle it, which will be easy with for example
shared_ptr. There is no insert_me(), and therefore not a chance for
insert_me() to impose extra (and probably confusing) assumption about how
multiple smart pointers should manage the life cycle.

If you insist using insert_me() with smart pointers, as as Benjamin pointed
out, you may need to use boost::enable_shared_from_this. Otherwise a
shared_ptr instantiated with a this pointer in insert_me() is very
dangerous, because it will eventually try to delete aa even if aa was
created on the stack.

--------------------------------------------------
From: "Hossein Haeri" <powerprogman_at_[hidden]>
Sent: Tuesday, September 21, 2010 8:16 PM
To: <boost-users_at_[hidden]>
Subject: [Boost-users] [PtrContainer] Inserting "this" Pointers

> Dear all,
>
> Is inserting "this" pointers into pointer containers valid? If so, what
> are the consequences? Would that need special care for example?
>
> TIA,
> --Hossein
>
>
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net