加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

类内的向量:处理复制构造函数和析构函数(C)

发布时间:2020-12-16 03:18:19 所属栏目:百科 来源:网络整理
导读:用“大3”(构造函数,复制构造函数,析构函数)来做一个简单的类: #include vectorusing 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. pub
用“大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(...) 
   }
}

我打算制作一个行星矢量,因此需要“大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.

如何正确删除质量和半径向量,以避免内存泄漏(甚至需要)?

解决方法

不,你不需要做任何事情,因为你没有管理任何资源.当你管理资源时,你只写三巨头,但是矢量是这样做的.这是与三大正确写的,你只是使用它.

这就是为什么单一责任原则是资源管理的关键:一旦你有一个正确管理资源的类,你可以简单地使用它,而不用再担心资源.始终从资源使用中分割资源管理.

你需要在管理类中编写的三大原因是因为默认的特殊成员通常会做错事(它们复制,分配,破坏值而不是值管理/指向).但是一旦你被资源包装了(像一个std :: vector),一切都很好.默认值将复制矢量,但正确写入复制.

顺便说一句,三巨头是在管理资源(复制和销毁资源)的背景下,而不是创建它们.所以它将是copy-constructor,copy-assignment和destructor,而不是默认构造函数.

有关您的信息,请执行以下操作:

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,并把它作为一个练习.

(记住你实际上并不需要这些.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读