以“big 3”(构造函数、复制构造函数、析构函数)的简单类:
#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(...)
}
}
我计划制作一个行星 vector ,因此需要“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.
如何正确删除质量和半径 vector ,以避免内存泄漏(我什至必须这样做)?
最佳答案
不,您不需要做任何事情,因为您不管理任何资源。您只在管理资源时编写三巨头,但 vector
正在这样做。 它是三巨头写得正确的那个,你就用它吧。
这就是为什么单一职责原则是资源管理中的关键:一旦您有某个类可以正确管理资源,您就可以简单地使用它,而无需再次担心该资源。 始终将资源管理与资源使用分开。
您需要在管理类中编写三巨头的原因是因为默认的特殊成员通常会做错事(他们复制、分配、破坏值而不是值管理/指向的内容。)但是一旦你资源被打包(就像在 std::vector
中一样),一切都很好。默认会复制 vector ,但是复制是正确写入的。
顺便说一句,三巨头是在管理资源(复制和销毁资源)的上下文中,而不是创建它们。所以它将是复制构造函数、复制赋值和析构函数,而不是默认构造函数。
供您引用,以下是您的操作方法:
class planets
{
public:
// ...
//copy constructor
planets(const planets &p) : // use an initialization list to initialize
mass(p.mass), // copy-construct mass with p.mass
radius(p.radius) // copy-construct radius with p.radius
{
// what you had before just made a local variable, copy-constructed
// it with p.xxx, then got released (nothing happened to your members)
}
//destructor
~planets()
{
// nothing to do, really, since vector destructs everything
// right for you, but you yes, you would delete any resources
// you managed here
}
};
但不要忘记复制赋值运算符。我推荐 copy-and-swap idiom ,并将其作为练习留给您。
(请记住,您实际上并不需要这些。)
关于c++ - 类 : handling copy constructor and destructor (C++) 内的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3510662/