0

I have distilled the essence of my problem! example:

struct arrayInside {
    int* arr;

    arrayInside(int n) {
        arr = new int[n];
    }
    ~arrayInside() {
        delete arr;
    }
};

void main() {
    std::vector<arrayInside> vec;

    for (int i = 10; i < 20; i++) {
        vec.push_back(arrayInside(i));
    }
}

this results in a crash because upon each push_back into the vector, the destructor is called on something and in the end, it ends up trying to delete addresses don't in fact contain the array created in the constructor.

I could circumvent this by instead storing pointers of arrayInside but this is about convenience, I don't want to have to loop through the vector again to delete every item. How can I make the arrayInside class vector proof?

user81993
  • 6,167
  • 6
  • 32
  • 64
  • You have to provide relevant copy-constructor (or move if C++11), because default does not work in this case. – Zereges Feb 28 '16 at 21:59

2 Answers2

0

The pointer gets copied over and then it tries to delete it twice.

Zereges gave the answer in the comment: A copy constructor could delete and recreate properly and a move constructor would be best.

wally
  • 10,717
  • 5
  • 39
  • 72
0

std::vector will copy (or move) the instances it's storing whenever it's resizing its internal storage. This may happen due to adding instances to the vector.

To solve this you need to implement a copy constructor and a copy assignment operator, and probably also their equivalents for moving (since C++11).

I'm assuming that you're writing that code for learning purposes. Production code shouldn't need any of these (rule of zero).

Further reading: http://en.cppreference.com/w/cpp/language/rule_of_three

Daniel Jour
  • 15,896
  • 2
  • 36
  • 63