【问题标题】:How to deep copy in initialization List incase of const variable在 const 变量的情况下如何在初始化列表中进行深度复制
【发布时间】:2021-07-18 16:31:10
【问题描述】:

我知道构造函数中的深拷贝可以通过以下方式完成。

class student{
    public:
    int age;
    int rollno;
    char *name; 
    
    
     student(int rollno,int age, char *name){
        this->age=age;
        this->rollno=rollno;


        //deep copy 
        this->name=new char[strlen(name)+1];
        strcpy(this->name,name);
    }
 };

但我想使用初始化列表来做(如果变量是 const 类型)这是我的新类:

    class student{
       public:
        const int age;
        int rollno;
        const char *name; // used pointer to avoid wastage of space or less space getting assigned 
      
        student(int age,int rollno, char *name): rollno(rollno),age(age),name(name){
            
        }
    };

现在我正在通过以下方式访问这个类

#include<bits/stdc++.h>
#include "student.cpp"
using namespace std;

int main(){

 
    char name[]= "jerry";
    student s(12,1,name);
    cout<<s.name<<endl; //gives jerry
    name[0]='m';
    cout<<s.name<<endl; // gives merry
}

所以我想要的是对象变量的值不应该改变。这意味着它应该在两个 cout 语句中打印 jerry 。有类似的问题,但我没有得到那个或如何在这种特殊情况下实施。

【问题讨论】:

  • 作为一个快速提示,const 成员变量非常令人头疼,因为它的好处有限。将成员设为私有会为您省去很多麻烦。

标签: c++ constructor initializer-list


【解决方案1】:

您应该使用std::string 来存储字符串。

有了它,你的班级看起来像这样:

class student{
   public:
   const int age;
   int rollno;
   const std::string name; 
  
   student(int age, int rollno, std::string name): 
     rollno(rollno), age(age), name(std::move(name)) {}
};

这不仅为您提供了您想要的东西,而且最重要的是:

  • 通过使用 RAII,它还可以修复原始代码中存在的内存泄漏问题
  • 由于在 std::string 中进行了一些花哨的优化,这将使您的代码在处理小字符串时更快并使用更少的内存,因此即使是您的“避免浪费空间”问题也得到了解决。

【讨论】:

  • 感谢它现在工作正常,内存泄漏是我从未意识到的。在这种情况下,我们可以通过使用字符串来避免麻烦,但是如果我们在具有深拷贝的构造函数中使用初始化列表作为 int 数组指针呢?
  • @SuryanshSingh 那么您将使用std::vector&lt;int&gt; 而不是int*。你不应该使用new,除了一些相当奇特的情况。
【解决方案2】:

为什么不使用字符串?我认为这可以解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2017-04-22
    • 2016-10-07
    • 1970-01-01
    • 2013-01-07
    相关资源
    最近更新 更多