Is the "giving" reference to 'this' inside the constructor okay?

my code is:

Scene::Scene(const std::string &scene_file) : ambient_light(0, 0, 0), background(0, 0, 0){ scene_parser parser(*this); parser.parse(scene_file); } 

scene_parser is a scene friend, and in the parse method it refers to the (r / w) members of the Scene. Will this cause problems?

+6
c ++
source share
4 answers

In your specific example, there are no problems.

Typically, the problem with issuing this links is that the lifetimes of two objects are not exactly aligned, and the other object may try to access the specified object after it has already been destroyed.

In your example, the scene_parser object is on the stack, so its lifetime expires at the end of the Scene constructor. It is not possible to try to access a non-existent object using this this help you provided, so no problems.

+4
source share

Yes, it’s ok to give a link to this . However, you usually want to do this when another object will use the pointer later. Your use case looks like it will use Scene immediately before the constructor completes that very slippery slope.

Right now you are not setting any invariants after calling parse , so that should be fine, but it is also fragile and easy for future changes to introduce breakage.

+8
source share

It depends.

Inside the body of the constructor (that is, as soon as the list of initializers is executed), the object is considered to be "fully constructed" to the current type. Therefore, you can reference *this , but any calls to virtual functions will not use overridden functions in derived classes.

+1
source share

All your subobjects (members and bases) are built according to the first statement in the body of the constructor. If your object is in the “correct state” (which is part of the definition of your class, sometimes called the “class invariant”), at the moment you can consider it as a fully constructed object and do something with it. However, virtual search works slightly different than you might expect or require: if it is a base class (and therefore this object is a subobject of something else), the final type has not yet been "assigned". For example, this is one way to call pure virtual methods and get a runtime error (if these methods have no definitions, anyway).

A more interesting situation uses this in the constructor initializer; which has some reservations, but it is also in front of the body of the constructor.

0
source share

All Articles