mardi 17 mai 2022

Why isn't the user-defined copy constructor invoked? [duplicate]

See the code in http://cpp.sh/8bsdl:

// copy constructor: deep copy
#include <iostream>
#include <string>
using namespace std;

class Example5 {
    string* ptr;
  public:
    Example5 (const string& str) : ptr(new string(str)) {cout << "constructor" << '\n';}
    ~Example5 () {delete ptr;}
    // copy constructor:
    Example5 (const Example5& x) : ptr(new string(x.content())) {cout << "copy constructor" << '\n';}
    // access content:
    const string& content() const {return *ptr;}
};

int main () {
    // cout << "copy constructor" << '\n';
  Example5 foo ("Example1");
  Example5 baz ("Example2");
  Example5 bar = foo; // default copy constructor
  bar = baz; // default copy assignment

  cout << "bar's content: " << bar.content() << '\n';
  return 0;
}

I defined a customized copy constructor, but it seems that it never gets called (In fact, the program doesn't produce any output, not even from the constructor...).

The same thing happens when I commented out line 12 where I hope to invoke the default copy constructor. Can anyone tell me what's wrong here?

Aucun commentaire:

Enregistrer un commentaire