How to handle 'this' pointer in constructor?

Posted by Kyle on Stack Overflow See other posts from Stack Overflow or by Kyle
Published on 2010-03-24T18:47:17Z Indexed on 2010/03/24 19:03 UTC
Read the original article Hit count: 220

I have objects which create other child objects within their constructors, passing 'this' so the child can save a pointer back to its parent. I use boost::shared_ptr extensively in my programming as a safer alternative to std::auto_ptr or raw pointers. So the child would have code such as shared_ptr<Parent>, and boost provides the shared_from_this() method which the parent can give to the child.

My problem is that shared_from_this() cannot be used in a constructor, which isn't really a crime because 'this' should not be used in a constructor anyways unless you know what you're doing and don't mind the limitations.

Google's C++ Style Guide states that constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. This solves the 'this-in-constructor' problem as well as a few others as well.

What bothers me is that people using your code now must remember to call Init() every time they construct one of your objects. The only way I can think of to enforce this is by having an assertion that Init() has already been called at the top of every member function, but this is tedious to write and cumbersome to execute.

Are there any idioms out there that solve this problem at any step along the way?

© Stack Overflow or respective owner

Related posts about c++

Related posts about boost