Skip to main content
gamedev.net
🔒 Locked

shared_ptr conversion problem

Started by Prune Mar 23, 2009 at 12:38 PM 3 replies 1k views
Original Post
Prune
Prune
VC++ 9 using namespace tr1; ... vector > mods; mods.push_back(libs[0].GetModuleP(log, &inq, &outq, SW, SH, params0)); gives: error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from 'Module *' to 'const std::tr1::shared_ptr<_Ty> &' ( GetModule() returns Module *) What's the right way to do it?
"But who prays for Satan? Who, in eighteen centuries, has had the common humanity to pray for the one sinner that needed it most?" --Mark Twain

~~~~~~~~~~~~~~~Looking for a high-performance, easy to use, and lightweight math library? http://www.cmldev.net/ (note: I'm not associated with that project; just a user)
SiCrane
SiCrane
mods.push_back(shared_ptr(libs[0].GetModuleP(log, &inq, &outq, SW, SH, params0)));
demonkoryu
demonkoryu
Does this work?

mods.push_back(shared_ptr<Module>(libs[0].GetModuleP(log, &inq, &outq, SW, SH, params0)));
Prune
Prune
Thanks.
"But who prays for Satan? Who, in eighteen centuries, has had the common humanity to pray for the one sinner that needed it most?" --Mark Twain

~~~~~~~~~~~~~~~Looking for a high-performance, easy to use, and lightweight math library? http://www.cmldev.net/ (note: I'm not associated with that project; just a user)
chairthrower
chairthrower
Would it make sense to make GetModule() return a shared_ptr rather than the raw pointer ? You run the risk that somewhere else in the code, the raw pointer will again be assigned to a shared_ptr which creates an instant bug. The issue is that you create two systems with responsibility for memory management, rather than one underlying reference count that gets transmitted between shared_ptr copies and assignments. If GetModule can potentially be called more than once while returning the same pointer value there will be a problem.

By example,
struct A{       A() { std::cout << "constructor" << std::endl; }    ~A() { std::cout << "destructor" << std::endl; }};int main(){       using boost::shared_ptr;    shared_ptr< A> a, b;    A *p = new A;    a = shared_ptr< A>( p);    b = shared_ptr< A>( p);}


In this case A's constructor is called once, but the destructor is called twice which is obviously bad form.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.