Please download the code from Friday and this text file! We will be working off of the code in 0-destructors Constructs and Destructors - Code Modification: In the makefile add to the gcc flags - -fno-elide-constructors - When and where objects created and destroyed in C++ is not straightforward - When is the constructor and destructor called for: - Stack allocated objects? - Heap allocated objects? - What is the ordering of creation and destruction when creating objects with an embedded object? - Construction - Destruction - Why is destructor being called 4 times on local? - Run valgrind (make run): - What happens? - Fix: - Why does the fix fail? Copy constructors - Reason we see the destructor being called multiple times on the same object - Automatically generated by the compiler unless you write your own - C++ invokes the copy constructor during: 1. Explicit copy 2. Pass by value argument in a function 3. Return value in a function (**See below) - Code Modification: Define Example's copy constructor with a print statement - In Example.h add a declaration of the copy constructor (public) Example(const Example &o); - In Example.c add a definition for the copy constructor Example::Example(const Example &o) : id(o.id), strPtr(o.strPtr), other(o.other) {     cout << "Example copy constructor" << toString() << endl;     } - This is just a naïve shallow copy to imitate the synthesized one + the print - Default version does a shallow copy of fields - Why is this problem? - Solution? (Will discuss in lecture more) - What's wrong with this? Example(Example other) Copy elision - Copy constructors can be optimized away when the compiler can guarantee it produces the same observed behavior - Sometimes subtle when the compiler can do this but you should know this case: - Return value optimization - For return by value functions the copy from temporary return value of the function to the named return value is omitted - Directly constructing the object into the storage of the named return value - Also emitted if there is no named return value - Is true even if there are side effects (ex. Print statements in the copy constructor) - Example e = sub(local) - sub(local) - Takeaways: return by value for objects has no copy penalty - Can force compiler not to optimize with compiler flag -fno-elide-constructors - Code Modification: remove the -fno-elide-constructors flag - What happened to the output?