I like this idea

Playing Semantics

In this second part, we take a look at what happens when an object stores a reference to another one, effectively not controlling its lifetime. An rvalue reference is required as an argument in order to convey the “I am taking control of the object’s lifetime” semantics. Of course, a shared_ptr or unique_ptr could have also been used and some might prefer it, especially if access to the referred object is still required outside the context of the newly constructed one.

We assume the same ExpensiveToCopy class from part 1. We first introduce the KeepsEtcRef class, instances of which need to refer to an ExpensiveToCopy instance.

class KeepsEtcRef { public: KeepsEtcRef = delete; KeepsEtcRef(ExpensiveToCopy& etcArg): etc(etcArg) { cout < "KeepsEtcRef: costructor" < endl; } ~KeepsEtcRef { cout < "KeepsEtcRef: destructor" < endl; } void print { etc.print; } private: ExpensiveToCopy& etc; };

Let’s instantiate both classes making sure that the ExpensiveToCopy instance doesn’t get destructed while the KeepsEtcRef instance is still around.

{ cout < "KeepsEtcRef" < endl; ExpensiveToCopy etc; KeepsEtcRef k(etc); k.print; }

// output KeepsEtcRef ExpensiveToCopy (1.0): constructor KeepsEtcRef: costructor ExpensiveToCopy (1.0): contains 2 messages KeepsEtcRef: destructor ExpensiveToCopy (1.0): destructor

What if the Large instance went away somehow?

{ cout < "KeepEtcRef outlives ExpensiveToCopy" < endl; ExpensiveToCopy* etc = new ExpensiveToCopy; KeepsEtcRef k(*etc); delete etc; k.print; }

KeepEtcRef outlives ExpensiveToCopy ExpensiveToCopy (1.0): constructor KeepsEtcRef: costructor ExpensiveToCopy (1.0): destructor ExpensiveToCopy (0.0): contains 0 messages KeepsEtcRef: destructor

No surprise! The data is gone. The KeepsEtcRef object outlives that to which it maintains a reference. While the program doesn’t crash in this case (since the vector object still exists), something more catastrophic could have happened. Resources were released. We could have ended up with an ugly crash. Can move help us? Let’s rewrite the container class…

Related video
SemanticsSpanish
SemanticsSpanish
Semantics Lecture-Intro to Linguistics (Ling 200) Rice
Semantics Lecture-Intro to Linguistics (Ling 200) Rice ...
Computational Linguistics I: Lexical Semantics
Computational Linguistics I: Lexical Semantics
Morgan Kaufmann Blondie24: Playing at the Edge of AI (The Morgan Kaufmann Series in Artificial Intelligence)
Book (Morgan Kaufmann)
  • David B. Fogel
  • math
  • technology
Interesting facts
Related Posts