$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
Subject: Re: [Boost-users] Copy a smart pointer into allocated memory
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2009-06-12 11:02:31
AMDG
Tiago Alves wrote:
> 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).
>
> Out of desperation, i did this:
> memcpy(camera,cameraPtr,sizeof(boost::weak_ptr<Obj>));
>
> Which seems to work but it stinks. It's copying an object with memcpy 
> instead of using its constructor.
>
> Is there a better way to do this?
Use placement new.
new(camara) boost::weak_ptr<Obj>(obj_share_ptr);
In Christ,
Steven Watanabe