1
  #include <iostream>

    using namespace std;

    class Shallow {
    private:
        int *data;
    public:
        void set_data_value(int d) { *data = d; }
        int get_data_value() { return *data; }
        // Constructor
        Shallow(int d);
        // Copy Constructor
        Shallow(const Shallow &source);
        // Destructor
        ~Shallow();
    };

    Shallow::Shallow(int d) {
        data = new int;
        *data = d;
    }

    Shallow::Shallow(const Shallow &source) 
        : data(source.data) {
            cout << "Copy constructor  - shallow copy" << endl;
    }

    Shallow::~Shallow() {
        delete data;
        cout << "Destructor freeing data" << endl;
    }

    void display_shallow(Shallow s) {
        cout << s.get_data_value() << endl;
    }

    int main() {

        Shallow obj1 {100};
        display_shallow(obj1);

doing alright until here
Shallow obj2 {obj1}; here where my program stop doing ok obj2.set_data_value(1000); enter code here can anyone explain this to me in this point
return 0; } in the end of my program something going wrong

Antutu Cat
  • 105
  • 4
  • 4
    `int *data;`? Why a pointer? – Spencer Mar 18 '20 at 21:13
  • 1
    If you use a naked owning pointer as a member variable, you are responsible for handling it properly. A debugger will be very useful. – Eljay Mar 18 '20 at 21:15
  • As a general rule of thumb: In modern C++, if you use `new` or `delete` you are (almost always) doing something wrong. – bitmask Mar 18 '20 at 22:23
  • This question has nothing to do with the Rule of Three. I wish people would actually read before closing. – Spencer Mar 18 '20 at 22:42

1 Answers1

1

The problem is that every call to Shallow::~Shallow deletes the data pointer's memory, but not every new Shallow allocates a new block of memory. Every delete needs to correspond to exactly one new. But

display_shallow(obj1);

1) creates a new temporary Shallow object (you pass to display_shallow by value) which uses the data pointer of obj1

2) destroys the temporary, which deletes the block of memory used by both the temporary and obj1

obj2 also shares obj1's pointer, which doesn't point anywhere anymore. When you try to call obj2.set_data_value(1000), you're dereferencing an invalid pointer, which is undefined behavior. You should consider yourself lucky that the program merely crashed, rather than launch a nuclear missile.

Spencer
  • 1,924
  • 15
  • 27