mercredi 21 décembre 2022

copying a string pointer from object x to another with (*this).ptr instead of x.ptr

So i am learning about C++ special members in details.

i was fiddling with codes and trying different ways, then came across to this:

#include <iostream>
#include <string>
using namespace std;

class Example5 {
    public:
    string* ptr;
  public:
    Example5 (const string& str) : ptr(new string(str)) {}
    ~Example5 () {delete ptr;}
    // copy constructor:
    Example5 (const Example5& x) : ptr(x.ptr) {}
};

int main () {
  Example5 foo ("Example");
  Example5 bar (foo);

  cout << foo.ptr << endl << bar.ptr;
  return 0;
}

this code showing a shallow copy of object with the expected result :

0x505348
0x505348

while this code does not appear to preform a shallow copy

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

class Example5 {
    public:
    string* ptr;
  public:
    Example5 (const string& str) : ptr(new string(str)) {}
    ~Example5 () {delete ptr;}
    // copy constructor:
    Example5 (const Example5& x) : ptr((*this).ptr) {}
};

int main () {
  Example5 foo ("Example");
  Example5 bar (foo);

  cout << foo.ptr << endl << bar.ptr;
  return 0;
}

with these results :

0x505348
0x505278 

isn't *this just points to the object and it's members ??

i was expecting same outcome.

Aucun commentaire:

Enregistrer un commentaire