newbie question on preferred method to use shared_ptrs

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; // ... } or ... int fun(void) { foo *temp = new int; dog.reset(temp); // ... } The first has the extra overhead of creating a second shared_ptr. The second worries me... It just seems like "reset" is not what I would call the method to do what I want to do (but maybe it is). Anyone care to help me out here? Thanks, Perry

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

On 2/15/06, Perry Smith
The first has the extra overhead of creating a second shared_ptr. The second worries me... It just seems like "reset" is not what I would call the method to do what I want to do (but maybe it is).
reset is exactly what you're looking for http://boost.org/libs/smart_ptr/shared_ptr.htm#reset int fun() { dog.reset( new int ); // ... } ~ Scott
participants (3)
-
me22
-
Perry Smith
-
Rush Manbert