|
Boost Users : |
From: Rush Manbert (rush_at_[hidden])
Date: 2006-02-15 20:05:07
Perry Smith wrote:
> Hi,
>
> I often have to "fight" with my C++ code and I must be missing a
> basic design characteristic of C++.
>
> Suppose there is a shared_ptr that has already been created. I now
> want to create an object with new and "give" it to shared_ptr to
> manage. I tend to do this:
>
> std::tr1::shared_ptr<int> dog;
>
> int fun(void)
> {
> int *temp = new int;
> dog = temp;
> // ...
> }
>
> This does not work. I've discovered two ways to achieve (I think)
> what I'm looking for:
>
> int fun(void)
> {
> std::tr1::shared_ptr<int> temp(new int);
> dog = temp;
> // ...
> }
Almost. What you want to do is this:
std::trl::shared_ptr<int> dog(new int);
which instantiates the object of interest and gives its address to the
shared ptr.
>
> or ...
>
> int fun(void)
> {
> foo *temp = new int;
> dog.reset(temp);
> // ...
> }
>
This works, but is clumsy. I believe the intent of reset is to change
the contained pointer value (and also decrement the use count for the
original contained pointer). I have also used it in the following way:
{
boost::shared_ptr<myObjectType> pMine; // Contains a NULL pointer value
// Do some stuff
if (test some boolean that doing some stuff created)
{ // Because this is true we create a new object
pMine.reset (new myObjectType (my constructor args));
}
// Do some more stuff
if (pMine)
{ // I created an object
}
else
{ // I didn't create an object
}
}
In case you haven't yet, take a look at:
http://www.boost.org/libs/smart_ptr/shared_ptr.htm
Hope it helps,
Rush
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