Thread: Using this pointer in constructor

  1. #16
    Registered User
    Join Date
    May 2008
    Quote Originally Posted by grumpy View Post
    Give me a pointer to a ModelReader, I can do anything I like to the ModelReader which is pointed at, regardless of whether it is owned by your Model class or not.
    Oh I see. For example, you could delete the object at that address. That wouldn't be very nice to everyone else holding a pointer to the ModelReader. Would using a std::shared_ptr resolve all of the troubles?

  2. #17
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Portland, OR
    Quote Originally Posted by jason_m View Post
    Thanks for the feedback. My specific take away from this is it is fine to store the pointer; it is not okay to dereference it or try to access any members through it.
    That's superstition.

    It is unsafe for some other object to access the object while it is being constructed, as that other object cannot know the details of initialization.

    So, if you pass "this" to some object/function in a constructor's initialization list, that object/function should not access the object pointed to by that pointer, because it isn't constructed yet. This has nothing to do whether an object can access its own internals during construction -- if it could not, how could one implement a constructor?

    But this isn't due to some unknown and unknowable behavior on the part of the compiler. In fact, the compiler makes a number of guarantees about how things happen during construction. The members in the constructor initialization list will be initialized in the order they are declared in the class declaration. The statements inside the body of the constructor will be executed according to the same rules about expressions and sequence points that all other code abides by. The moment at which the vtable is initialized is a bit less clear, however, so objects should not invoke virtual functions on themselves during construction.

    Accessing an uninitialized or partly-initialized object is always a bad thing. It is not limited to the this pointer in a constructor.
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 06-23-2012, 10:47 PM
  2. Replies: 4
    Last Post: 02-09-2012, 08:51 PM
  3. Replies: 4
    Last Post: 01-26-2012, 12:55 AM
  4. pointer conversion problems with a copy constructor
    By stanlvw in forum C++ Programming
    Replies: 8
    Last Post: 01-14-2008, 12:06 AM
  5. Copy constructor error, 'this' pointer conversion
    By bennyandthejets in forum C++ Programming
    Replies: 6
    Last Post: 01-08-2004, 05:18 PM