|
Boost Users : |
Subject: Re: [Boost-users] Constructing a shared pointer from a const pointer
From: veerus (veeranjaneyulu.sadhanala_at_[hidden])
Date: 2009-11-11 06:02:19
I got out of the problem.
The signature of bar is bar( int xpointer );
and foo calls bar( (int) &x).
All I have to pass to bar is an identity of x.
Johan Nilsson-4 wrote:
>
> veerus wrote:
>> Hi All,
>>
>> I have been in trouble for a day solving this seemingly simple
>> problem - constructing shared_ptr<X> from const X& without copying
>> the X object.
>>
>> The programming logic does not allow me to construct the shared_ptr
>> like this: SX x = SX( new X( x ) );
>>
>> Consider the following piece of code:
>>
>> void foo( const X& x )
>> {
>> typedef shared_ptr<X> SX;
>> SX px = SX( &x );
>>
>> bar( px );
>> }
>>
>> The compiler gives the following error:
>> In shared_ptr.hpp at line 184: 'initializing' cannot convert from
>> 'const X *' to 'X*'.
>
> To make it compile, you could simply change the typedef to "typedef
> shared_ptr<X const> SX;".
>
> However, the code is suspect - depending on how the caller of foo declares
> and manages the variable used as "x", you're likely to either encounter a
> delete of a (invalid reference to a) stack object sooner or later, or
> perhaps a double delete. If I saw the above during a code review I would
> say
> foo needs to be redesigned.
>
> If you're relying on identity here, or if X is non-copyable, and want to
> transfer ownership of "x" into "bar" you could define foo as:
>
> void foo(std::auto_ptr<X> px)
> {
> bar(shared_ptr<X>(px));
> }
>
> [It's hard to tell without knowing the full context]
>
> / Johan
>
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>
>
-- View this message in context: http://old.nabble.com/Constructing-a-shared-pointer-from-a-const-pointer-tp26296800p26299489.html Sent from the Boost - Users mailing list archive at Nabble.com.
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