I am just tapping into C++ and probably missing something obvious here. I have a class that dynamically allocates an array and I would like to put its objects into a vector. Since the array has to be freed in the destructor and it is called by vector.push_back()
I read that I have to define a copy- as well as move-constructor to avoid memory corruption errors. However, the example below still gives me a double free or corruption (fasttop)
error.
#include <iostream>
#include <vector>
using namespace std;
class bla {
public:
int* arr;
bla() {
arr = new int[10];
for (size_t i = 0; i < 10; i++) {
arr[i] = 42;
}
}
bla(bla&& b) : arr(b.arr) {
cout << "move" << endl;
}
bla(const bla& b) : arr(b.arr) {
cout << "copy" << endl;
}
~bla() {
cout << "delete" << endl;
delete[] arr;
}
};
int main() {
vector<bla> blas;
blas.reserve(5000);
blas.push_back(bla()); // same result with emplace_back
blas.push_back(bla()); // same result with emplace_back
blas.push_back(bla()); // same result with emplace_back
return 0;
}
Could anybody explain what I'm doing wrong and maybe also provide an example of how to add objects with dynamic memory to vectors (I know that I can use pointers, but from what I read it should also work with the objects themselves).
I run g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
with -Wall -std=c++11 -lm
UPDATE 1:
Running the same code with the same flags on g++ 7.4.0
does not result in the double free error. Does anybody have an idea why?
UPDATE 2: For posterity, since apparently there are not that many minimal examples implementing the rule of 5 for dynamic arrays floating around. This is how you should do it (please correct me, if I'm wrong):
#include <iostream>
#include <vector>
using namespace std;
class bla {
public:
int* arr;
bla()
: arr(nullptr)
{
arr = new int[10];
for (size_t i = 0; i < 10; i++) {
arr[i] = 42;
}
}
~bla() {
cout << "delete" << endl;
delete[] arr;
}
// deep copy constructor
bla(const bla& other) {
cout << "copy" << endl;
arr = new int[10];
for (size_t i = 0; i < 10; i++) {
arr[i] = other.arr[i];
}
}
// deep copy assignment
bla& operator = (const bla& other) {
cout << "copy assignment" << endl;
if (&other != this) {
delete[] arr;
arr = new int[10];
for (size_t i = 0; i < 10; i++) {
arr[i] = other.arr[i];
}
}
return *this;
}
// move constructor
bla(bla&& other)
: arr(other.arr) {
cout << "move" << endl;
other.arr = nullptr;
}
// move assignment
bla& operator = (bla&& other){
cout << "move assignment" << endl;
if(&other != this) {
delete[] arr;
arr = other.arr;
other.arr = nullptr;
}
return *this;
}
};
int main() {
vector<bla> blas;
cout << "=========\nstart pushs\n=========" << endl;
blas.push_back(bla());
blas.push_back(bla());
blas.push_back(bla());
cout << endl << "=========\nend pushs\n=========" << endl << endl;;
cout << "for each:" << endl;
for (bla b : blas) {
cout << b.arr[0] << endl;
}
cout << endl;
cout << "native for:" << endl;
for (size_t i = 0; i < 3; i++) {
cout << blas[i].arr[0] << endl;
}
return 0;
}