|
View:
New views
4 Messages
—
Rating Filter:
Alert me
|
|
|
Constructing a shared pointer from a const pointerHi 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*'. Please suggest any procedure to solve this problem. |
|
|
Re: Constructing a shared pointer from a const pointerTo add more to the above query,
assume that 'bar' is defined as follows: map<SX, SX> m; bar( SX px ) { m.insert( pair<SX, SX>(px, someFunction( px ) )); } Can we do with a weak_ptr<X> instead of shared_ptr<X> ? Thanks |
|
|
Re: Constructing a shared pointer from a const pointerveerus 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@... http://lists.boost.org/mailman/listinfo.cgi/boost-users |
|
|
Re: Constructing a shared pointer from a const pointerI 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.
|
| Free embeddable forum powered by Nabble | Forum Help |