Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle 'this' pointer in constructor?
    primarykey
    data
    text
    <p>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 <code>shared_ptr&lt;Parent&gt;</code>, and boost provides the <a href="http://boost.org/doc/libs/release/libs/smart_ptr/enable_shared_from_this.html" rel="noreferrer"><code>shared_from_this()</code></a> method which the parent can give to the child.</p> <p>My problem is that <code>shared_from_this()</code> 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.</p> <p>Google's C++ Style Guide <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Doing_Work_in_Constructors#Doing_Work_in_Constructors" rel="noreferrer">states</a> 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.</p> <p>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. </p> <p>Are there any idioms out there that solve this problem at any step along the way?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload