0

I was wondering what is happening internally when assigning an anonymous object temporary to a named object:

#include <iostream>

class Object {
public:
  Object (void) {
    this->PrintAddress();
  }
  Object (const Object& another_object) {
    std::cout << "Copy constructor is called!\n";
  }
  ~Object (void) noexcept {}
  void PrintAddress (void) const {
    std::cout << "Object Address: " << this << '\n';
  }
};

int main (int arg_count, char* arg_vector[]) {
  // The following line:
  Object object = Object();
  object.PrintAddress();
  return 0;
}

Compiling and executing the resulting binary shows that the copy constructor is not called and both the named object ('object') and the RHS temporary have the same address meaning they are the same object. I somehow feel like the compiler associates the temporary to the name hence why no constructor is executed (besides when creating the RHS temporary). To better see this, take a look at the following:

Object object (Object()); // Line 1
object.PrintAddress() // Line 2

Notice that although line 1 has the same syntax as an object that performs a copy constructor, it also has a syntax resembling a function pointer. Commenting Line 2 doesn't affect the ability of the program to compile and yet uncommenting Line 2 (assuming I just created an Object named object) yield a compile error (likely due to the fact that you cannot execute member functions on a function pointer).

Sorry if this has dragged on for too long, but what is happening internally when you do this?

Thank you for your time!

R34
  • 59
  • 6
  • 3
    Search for "copy elision". Basically the compiler is allowed (and since C++17 required) to optimize out the copy. – nwp Oct 18 '17 at 15:51
  • Wow! Thank you so much. I'll read more into this. For the mean time feel free to school me with more details if you are generous enough to do so. – R34 Oct 18 '17 at 15:54
  • @R34 There are a lot of details about it [here](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – Steve Oct 18 '17 at 15:57
  • @Steve Thank you. Appreciate the link. – R34 Oct 18 '17 at 15:59

0 Answers0