Beginner's shared_ptr question...

(g++ 3.3.5, boost 1.32) I have a program as follows: Header: //multiple include guard omitted for clarity #include <boots/shared_ptr> class someOtherClass; class MyClass { public: MyClass(); void init(); . . . private: boost::shared_ptr <someOtherClass> spOther; . . . }; Implementation #1: #include <MyClass.hpp> #include <someOtherClass.hpp> MyClass::MyClass() { init(); } void MyClass::init() { spOther(new someOtherClass(this)); } Implementation #2: #include <MyClass.hpp> #include <someOtherClass.hpp> MyClass::MyClass():spOther(new someOtherClass(this)) { } Question: Why does implementation #2 fail to compile with the error: error: no match for call to '(boost::shared_ptr<someOtherClass>)(someOtherClass*)' ? yet implementation #2 compiles fine? Please help me understand what going on here...is it possible to get implementation #2 to compile or is it 'bad code'? Thanks

On Sun, 19 Nov 2006 17:47:55 +0000, "Martin Waller" <martinej.waller@ntlworld.com> said:
Implementation #1: MyClass::MyClass() { init(); }
void MyClass::init() { spOther(new someOtherClass(this)); }
Implementation #2: MyClass::MyClass():spOther(new someOtherClass(this)) { }
Question:
Why does implementation #2 fail to compile with the error:
error: no match for call to '(boost::shared_ptr<someOtherClass>)(someOtherClass*)' ?
yet implementation #2 compiles fine?
Please help me understand what going on here...is it possible to get implementation #2 to compile or is it 'bad code'?
(Your references are mixed up here - I'm assuming implementation #1 is the problematic one.) Implementation #2 should work - you're using the constructor's initialiser list to assign to the spOther member, using the shared_ptr's constructor. Implementation #1 attempts to call a method of the shared_ptr type with a parameter of type someOtherClass* (as returned by new). shared_ptr doesn't have any method matching that signature so the compiler gives an error. A more correct implementation of init would be: void MyClass::init() { // either spOther = shared_ptr<someOtherClass>(new someOtherClass(this)); // or spOther.reset(new someOtherClass(this)); } Dave. -- Dave Slutzkin Melbourne, Australia daveslutzkin@fastmail.fm

Martin Waller wrote:
#include <MyClass.hpp> #include <someOtherClass.hpp>
MyClass::MyClass() { init(); }
void MyClass::init() { spOther(new someOtherClass(this));
You can not call a constructor here. spOther has already been default constructed. Instead you should use the reset member function: spOther.reset(new someOtherClass(this));
}
participants (3)
-
Dave Slutzkin
-
Johan Råde
-
Martin Waller