Destructor crashing program for custom vector class because of overloaded = operator

Hi,

I am trying to make a custom vector class for strings.

Here's my current overloaded assignment operator for the class..

myStringVector& myStringVector::operator=(const myStringVector& data){
this->reserve(data.size());
this->last = uninitialized_copy(data.base, data.last, this->last);
return *this;
}

here is what reserve looks like,

void myStringVector::reserve(int n){
if(!base){
base = allocate<string>(n);
last = base;
limit = base+n;
}
else{
string *p = allocate<string>(n); //new base
string *q = p; //new last
limit = p + n; //new limit
string *i = uninitialized_copy(base, last, q);
destroy(i);
deallocate(base);
base = p; //update base
last = q; //update last
}
}

and here is uninitialized_copy

template<typename T>
inline T* uninitialized_copy(T const* first, T const* last, T* out)
{
while (first != last) {
construct(out, *first);
++out;
++first;
}
return out;
}

this is my destructor...

myStringVector::~myStringVector(){
if(!base){
//do nothing
}
else{
base = initialized_destroy(base, limit);
deallocate(base);
deallocate(last);
deallocate(limit);
}
}

If you need any other bits of my code, let me know I don't want to put up a wall of code initially.

THE PROBLEM:
The program is crashing after leaving this scope...


{
myStringVector v1 {"a", "b", "c"};
myStringVector v2;
v2 = v1;
assert(v1 == v2);
std::cout << "Passed copy assign" << std::endl;
}

When I added cout statements to my destructor, I noticed it was only called once after leaving this scope (I believe it should've been called twice). But the big problem is that the program is crashing after leaving this scope.

Im pretty new to coding and not really sure how to handle such a bug. Any advice is appreciated.
Last edited on
Without minimum reproducible code it is hard to locate this bug. I guess that may be some kind of soft copy in assign operator, that eventually lead to crash when program tries to delete already deleted object.
I'm fairly new to C++ myself and I've already run into the following problem. I had a destructor in a derived class that was deleting data that was already being deleted in the base class. The fix was to get rid of that part of that particular destructor. In case you haven't found this out yet, deleting the same pointer twice is bad mojo (i.e. crashtown).

One possible workaround is to zero out pointers after deleting them, as you can delete a null pointer all you like. HTH,

Lars
Topic archived. No new replies allowed.