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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With