Boost logo

Boost Users :

Subject: Re: [Boost-users] Copy a smart pointer into allocated memory
From: Peter Dimov (pdimov_at_[hidden])
Date: 2009-06-12 11:08:41


Tiago Alves:
> Hi, and sorry for the probable newbieness of this question!
>
> I want to put weak_ptr into a piece of memory previously allocated.
>
> this is my code:
>
> // construct a weak_ptr from a share_ptr
> boost::weak_ptr<Obj>* cameraPtr = new boost::weak_ptr<Obj>(obj_share_ptr);
> // lua_newuserdata allocs memory and returns a pointer to it, just like
> malloc.
> boost::weak_ptr<Obj>* camera =
> static_cast<boost::weak_ptr<Obj>*>(lua_newuserdata(pLuaState,sizeof(boost::weak_ptr<Obj>)));
>
> Now i want camera to be a weak_ptr of ObjPtr.
> I tried different ways to do this, such as
> *camera = boost::weak_ptr<Obj>(obj_share_ptr);
> or
> camera->swap(*cameraPtr);
> or
> *camera = *cameraPtr;
>
> I think none of these work because in fact they all do a swap() between
> camera and cameraPtr. Since camera is just an malloc, it will try to swap
> dirty memory and segfault sometimes (yes, sometimes this worked).

In C++, the way to construct an object of type X into uninitialized memory
(pointed to by a pointer p) is called placement new:

    #include <new>

    new( p ) X;

In your case, you'd do:

void * p = lua_newuserdata( pLuaState, sizeof( boost::weak_ptr<Obj> ) );
new( p ) boost::weak_ptr<Obj>( obj_share_ptr );

The last line constructs a new weak_ptr in the memory at p from the
obj_share_ptr argument (same as cameraPtr in your original example, but
without the allocation.)

Later (probably in your 'gc' metamethod, whatever that is :-) ) you'll also
have to dispose of the weak_ptr object; this is done by invoking the
destructor:

p->~weak_ptr<Obj>();

In weak_ptr's case, you can also cheat and just reset() it, as its empty
state consists of two NULL pointers and can be garbage-collected with
impunity, but in principle, the proper way to end the lifetime of such an
object is to call the destructor.


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