Search code examples
c++destructorcopy-constructor

Destructor causing SegFault C++


class Pair {

public:

    int *pa,*pb;


    Pair(int a, int b) 
    {
        pa = new int(a);
        pb = new int(b);
    }

    Pair(const Pair& other) {
        int* pc = new int(*other.pa);
        int* pd = new int(*other.pb);
    }


    ~Pair() {
        delete pa;
        delete pb;
    }

};

In this program the compiler is producing a Segmentation fault(core dump) and after removing the destructor completely can we get the program to run without any errors so can anyone pls help me with this? Also even tho in the parameterized constructor I initialized the pointers the compiler gives warning that the point pa and pb are not initialized.


Solution

  • :Your copy constructor is creating two pointers and then just leaking them away. It never sets the member variables of the class.

    You might want to refer to the rule of three / five / etc, and it wouldn't hurt to delete the default constructor for clarity.

    class Pair {
    public:
        int *pa, *pb;
    
        Pair() = delete;
        Pair(int a, int b): pa{new int{a}}, pb{new int{b}} {}
        Pair(const Pair& other): pa{new int{*other.pa}}, pb{new int{*other.pb} {}
    
        ~Pair(){
            delete pa;
            delete pb;
        }
    };