When calling the copy constructor, the pointers refer to the same pointer. And when calling the destructor, re-deleting the pointer. The question is how to correctly implement the copy constructor, so that the pointer does not re-delete in the future.

#include <iostream> class Io { public: Io (int v) : val(v){}; virtual ~Io (){}; int getValue(){return val;} private: int val; }; class Count { public: Count (Io _io):io_ptr(new Io(_io)){}; virtual ~Count (){delete io_ptr;}; Count(const Count &_io) { std::cout << "COPPY" << std::endl; } Io* getIo()const{return io_ptr;} private: Io *io_ptr; }; int main (int argc, char const* argv[]) { Count c(Io(12)); Count c2(c); return 0; } 
  • Well, the question is what? - Harry
  • 6
    This is very bad. Need to fix. - avp
  • @Harry, question: how to fix the copy constructor? - Qwertiy
  • You are making something up. In the code you give, pointers will not refer to "the same pointer." In the code you cited, the copy constructor does not initialize the copy pointer at all; this pointer will contain unpredictable garbage after copying. Where you get "will refer to the same pointer" is not clear. - AnT

1 answer 1

For example:

 Count(const Count &_io):io_ptr(new Io(_io.io_ptr->getValue())) { std::cout << "COPPY" << std::endl; }