Switch from a regular C++ pointer to boost shared_ptr
Hi, I have a class like this: class A { private: B* b; public: A(); B& getB(); } A::A() { b = NULL; } B& A::getB() { if (b == NULL) { b = new B(); } return *b; } when I switch to use boost shared_ptr, i.e. switch from 'B* b' to 'shared_ptr<B> b' in A's class definition. I don't need to do 'b= NULL' in A's constructor, right? But why this line won't compile "b = new B();" ? I get this error: A.cpp:297: error: no match for 'operator=' in '((const A*)this)->A::xBlockMap = (((B*)operator new(128u)), (<anonymous>->B::B(((const A&)((const A*)this)), ((int)strict)), <anonymous>))' /usr/local/include/boost-1_35/boost/shared_ptr.hpp:194: note: candidates are: boost::shared_ptr<T>& boost::shared_ptr<T>::operator=(const boost::shared_ptr<T>&) [with T = B] Thank you for any help.
AMDG Meryl Silverburgh wrote:
when I switch to use boost shared_ptr, i.e. switch from 'B* b' to 'shared_ptr<B> b' in A's class definition.
I don't need to do 'b= NULL' in A's constructor, right?
Correct.
But why this line won't compile "b = new B();" ?
Use b.reset(new B()); In Christ, Steven Watanabe
I don't need to do 'b= NULL' in A's constructor, right?
Right.
But why this line won't compile "b = new B();" ?
The constructor you need for this conversion is declared as "explicit". Do it this way: typedef boost::shared_ptr<B> BPtr; B& A::getB() { if (!b) b = BPtr(new B()); return *b; // btw, do you really wish to return the reference? }
On Wed, Jul 16, 2008 at 12:13 PM, Igor R
I don't need to do 'b= NULL' in A's constructor, right?
Right.
But why this line won't compile "b = new B();" ?
The constructor you need for this conversion is declared as "explicit". Do it this way:
typedef boost::shared_ptr<B> BPtr; B& A::getB() { if (!b) b = BPtr(new B()); return *b; // btw, do you really wish to return the reference? }
Thank you. You said 'btw, do you really wish to return the reference?' , Can you please tell me what do you mean, like what kind of problems it will cause?
_______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users
AMDG Meryl Silverburgh wrote:
Thank you. You said 'btw, do you really wish to return the reference?' , Can you please tell me what do you mean, like what kind of problems it will cause?
The potential problem is if the reference outlives all the shared_ptrs. Whether this is an actual problem or not depends on how getB is used. If the result is a short-lived reference, then it's safe. If the result is saved somewhere, it's safer to return a shared_ptr to make sure that the object doesn't get destroyed from underneath you. In Christ, Steven Watanabe
participants (3)
-
Igor R
-
Meryl Silverburgh
-
Steven Watanabe