-2

Hello this block of code is not compiling for some reason and for the life of my I can't figure it out. It gives me an error when it calls the destructor could someone tell me why please

The error is:

Exception thrown test.exe has triggered a breakpoint"

#include <iostream>
using namespace std;
class X {
public:
    X(int i)
    {
        p = new (int);
        *p = i;
    }
    ~X() { delete p; }
    int* p;
};

int main()
{
    X x1(1);
    X x2(2);
    x2 = x1;
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64
barry
  • 19
  • 1
  • 5
    Please add the text of the error message. – cigien Oct 18 '20 at 16:07
  • 1
    You should provide a copy constructor and an overload for the assignment operator, otherwise the allocated pointer would be deleted twice, leading to that error. That's a runtime error and no compiler error BTW. – πάντα ῥεῖ Oct 18 '20 at 16:09
  • Related: [Default assignment operator= in C++ is a shallow copy?](https://stackoverflow.com/q/5096464/2402272) – John Bollinger Oct 18 '20 at 16:10
  • 2
    The fact that you were able to get that error in the first place indicates that your code was able to compile. Please change the title. – ElectricShadow Oct 18 '20 at 16:11

1 Answers1

0

Because you assign

x2 = x1;

the pointer will be copied from x1 to x2 and it attempts to delete the same object twice.

Sven Nilsson
  • 1,861
  • 10
  • 11