
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