Take a simple class with the “big 3” (constructor, copy constructor, destructor):
#include <vector>
using namespace std; //actually goes in the C file that links to this header file
...
class planets(){ //stores mass and radii data for planets in a solar system.
public:
vector <double> mass;
vector <double> radius;
//constructor
planets( int numObj ){
for(int i=0; i<numObj; i++){
mass.push_back(8.0); //some default values.
radius.push_back(2.0);
}
}
//copy constructor
planets(const planets &p){
vector <double> mass(p.mass); //copy vectors into new class.
vector <double> radius(p.radius);
}
//destructor
~planets(){
delete mass; //ERROR: (...) argument given to ‘delete’, expected pointer
~radius(); //also causes error: no match for call to(...)
}
}
I plan on making a vector of planets, thus the need for the “big 3”:
vector <planets> stars;
stars.push_back(planets(5)); //5 hypothetical planets of alpha centauri
stars.push_back(planets(8)); //our solar system. Used to be nine.
///etc.
How do I delete the mass and radius vectors properly, to avoid memory leaks (do I even have to)?
No, you don’t need to do anything because you aren’t managing any resources. You only write the Big Three when you’re managing a resource, but
vectoris doing that. It’s the one with the Big Three properly written, you just use it.This is why the single responsibility principle is key in resource management: once you have some class that properly manages a resource, you can simply use it without ever worrying about that resource again. Always split resource management from resource use.
The reason you need the Big Three written in a managing class is because the default special members typically do the wrong thing (they copy, assign, destruct values instead of what the values manage/point at.) But once you’re resource is wrapped up (like in a
std::vector), everything is just fine. The defaults will copy vector, but that copying is correctly written.By the way, the Big Three is in the context of managing resources (copying and destroying resources), not created them. So it would be copy-constructor, copy-assignment, and destructor, not default constructor.
For your information, here’s how you would do it:
But don’t forget the copy-assignment operator. I recommend the copy-and-swap idiom, and leave that as an exercise for you.
(Remember you don’t actually need these, though.)