Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is 'giving out' a reference to 'this' inside the constructor ok?

Tags:

c++

my code :

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 friend of Scene, and in the parse method it accesses(r/w) the members of Scene. Is this going to cause any problems?

like image 227
Bwmat Avatar asked Nov 10 '10 04:11

Bwmat


2 Answers

Yes, it's ok to give out a reference to this. However, you usually want to do that when the other object will use the pointer later. Your use case looks like it will use the Scene immediately, before the constructor completes, which is a very slippery slope.

Right now, you're not establishing any invariants after calling parse, so it should be ok, but it's also fragile and easy for future changes to introduce breakage.

like image 152
Ben Voigt Avatar answered Nov 07 '22 09:11

Ben Voigt


In your particular example, no problems should arise.

Generally the problem with giving out this references is that the lifetimes of the two objects don't exactly align and the other object could try to access the referred-to object after it has already been destroyed.

In your example, the scene_parser object is on the stack, so it's lifetime ends at the end of the Scene constructor. There is no possible way it could attempt to access a non-existent object via that this reference you provided, so no problems can arise.

like image 45
Drew Hall Avatar answered Nov 07 '22 08:11

Drew Hall