0

Let's say I have a class just like this:

class example{
    double * ptr;

    public:
        example();
        ~example();
};

with methods implemented:

example::example(){
    ptr = new double;
    *ptr = 0;
}
example::~example(){delete ptr;}

If, in main, I create a std::vector<example> v; and v.push_back(example());, I just get a segmentation fault due invalid deletes. I'm not really sure what's causing this and if there's a way to fix it.

Thanks in advance

1 Answers1

0

You should write copy/move constructors for raw pointers, default constructor just copies ptr by address. Thus, you have the same ptr value in example() temporary object and in the example inside vector. destructor is called for temporary example object, deletes ptr. Then example destructor is called from vector, it tries to delete ptr, which was already deleted by previous destructor call.

Alex
  • 1,047
  • 8
  • 21