Boost logo

Boost :

From: Michael Anderson (michael.anderson_at_[hidden])
Date: 2007-03-01 03:05:58


Michael Marcin wrote:
> Michael Anderson wrote:
>> Howdy everyone.
>> I have some code that uses pointers to member variables that I want to
>> switch to using boost::shared_ptrs, some of the code looks like this.
>>
>> class Bar {};
>> class Foo
>> {
>> public:
>> Bar bar;
>> };
>>
>> ...
>> Foo * fooptr = new Foo;
>> Bar * barptr = &Foo.bar;
>> ...
>>
>> So to make this work with shared_ptrs I can do this:
>>
>> class Bar {}
>> class Foo
>> {
>> public:
>> Foo() : bar(new Bar) {}
>> shared_ptr<Bar> bar;
>> };
>>
>> ...
>> <snip>
>>
>
> Pardon my ignorance but why not just use scoped_ptr<Bar>?
>
> - Michael Marcin
>

For example I want this to work... where ptr<Bar> is some kind of
smart (or otherwise) pointer to a bar object.

{
   ptr<Bar> barPtr;
   {
     ptr<Foo> fooPtr(new Foo);
     barPtr = fooPtr->bar;
     //A
   }
   barPtr->doSomething(); //B
   //C
}

Note that fooPtr goes out of scope at line A, but if the Foo object is
destroyed at A then line B is an error. Instead I want the Foo object to
exist until line C where both barPtr and fooPtr go out of scope.

I don't believe this will work with any combination of barPtr, the
internal Foo::bar, and fooPtr being scoped pointers... If there is a way
to get something equivalent to the above fragment of code to work and be
correct using scoped pointers I'd love to see it.

We can't use scoped pointers because there are other constraints on our
code than the simplistic example shown here. But any trick that causes
the above code to work for scoped pointers should equally work with
shared pointers.

Michael Anderson


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk