0

I have an object O1 which has pointer. I created another object O2 by copy constructor. The pointer address will be copied into the object O2. When i come out of scope of O2, it will be deleted. The destructor will delete the pointer as well. This make the pointers in object O1 become dangling. How to make sure that i delete the pointer only when i come out of O1.

In a short description, how to delete the object pointer only when no others are referring to that pointer directly or indirectly.

class info {
    public:
        char *buf;
        int len;
        info(int l) {
            len = l;
            buf = new char[len];
            buf[0] = 'h';
        }
        ~info() {
            delete[] buf;
        }
};
int main() {
    info O1(100);
    cout << O1.buf << "\n";
    {
        info O2(O1);
    }
    cout << O1.buf << "\n";
}

Here the destructor of O1 at the end of the main will get a SIGABT signal for trying to deallocate a memory referred by O1.buf which is already deleted through O2.

3 Answers3

5

Shared pointers are exactly what you need.

I also suggest you have a look at the other smart pointers available in the memory standard library.

Edit:

Note that as explained here you should use delete[] as a destructor for your smart pointers that own an array type.

Julien Lopez
  • 1,599
  • 5
  • 15
  • 23
1

To be specific about shared_ptr usage, the class info should be:

class info {
    public:
        std::shared_ptr<char> buf;
        int len;
        info(int l) {
            len = l;
            if(!buf) buf = std::shared_ptr<char>(new char[len], std::default_delete<char[]>());
            buf.get()[0] = 'h';
        }
        ~info() {
        }
};
int main() {
    info O1(100);
    cout << O1.buf << "\n";
    {
        info O2(O1);
    }
    cout << O1.buf.get() << "\n";
}
Julien Lopez
  • 1,599
  • 5
  • 15
  • 23
lulyon
  • 5,745
  • 7
  • 26
  • 46
0

It seems that what you need are shared pointers. They are a bit tricky to use for arrays, this answer tells how to.

Community
  • 1
  • 1
lisyarus
  • 13,729
  • 3
  • 40
  • 61