0

So I have following code:

struct obj {
  static int c;
  int myc;
  obj() : myc(c++) {
    std::cout << "ctor of " << myc << '\n';
  }
  obj(const obj&) : myc(c++){
    std::cout << "copy ctor of " << myc << '\n';
  }
  ~obj() {
    std::cout << "dtor of " << myc << '\n';
  }
};
int obj::c = 1;

int main(int argc, char** argv)
{
  obj x = obj();
}

The output is:

ctor of 1
dtor of 1

However when I set the copy constructor to private my code fails. Can You explain me please why I never see the std::cout from copy constructor?

  • 1
    TL;DR of the dupe. The compiler is allowed to turn `obj x = obj();` into `obj x;` as it should not affect the actual behavior of the code and is more efficient. This was only allowed pre C++17 if the copy constructor was not private. – NathanOliver Apr 14 '21 at 21:16
  • @NathanOliver ok but when copy constructor is private why is program crashing instead of using the 1st constructor? – Robert Kwiatkowski Apr 15 '21 at 06:23
  • Because the compiler is only allowed to do this conversion if the copy constructor is public. If it's private, that was a way to mark a class as not copyable, so allowing the transformation would break the semantics of the code. – NathanOliver Apr 15 '21 at 11:56

0 Answers0