繁体   English   中英

如何将 char* 复制到另一个 char* 并释放第一个而不影响第二个

[英]How to copy a char* to another char* and free the 1st without affecting the 2nd

我的代码如下。 最初它显示了一个错误,即相同的内存位置被释放了两次。即返回的对象 temp 被释放了两次(在返回和复制到 obj2 之后)。 因此,我重载了复制构造函数以在应对时拥有不同的内存。 然后错误消失了,但垃圾值存储在 obj2 而不是“ll”中。 然后我将 = 运算符 void 主线 2 从浅拷贝重载到深拷贝。 现在垃圾值消失了,但它有一个空值而不是“ll”。我不想评论 free() 或使用#include 中的任何函数。有人能说应该怎么做吗?

class CustomStringClass 
{
    private:
        char* Input;
   
    public:
        CustomStringClass (string Input){
          //Dynamic mem allocation done to char*Input and store the input
        }
    
        CustomStringClass Substring(int Start, int End){
          //Substring found as "ll" from "Hello"
          CustomStringClass temp("ll");
          return temp;
        }
    
        ~CustomStringClass(){
            free(this->Input);
         }
};

void main()
{

    CustomStringClass Obj1("Hello");
    CustomStringClass Obj2=Obj1.Substirng(2,3);

}

您需要分配新内存并将其转换为使用长度未知的原始 char 数组。

此外,通常建议不要使用“使用命名空间 std”,个人建议对函数参数和成员函数使用相同的名称,必须记住正确使用 this-> 只是自找麻烦。

//Also use references note to make unnecessary copies
CustomStringClass (const std::string& letsUseADifferentName){
    Input = new char[letsUseADifferentName.Length()];
    memcpy(Input, letsUseADifferentName.c_str(),  letsUseADifferentName.Length());
}

~CustomStringClass(){
    delete[] Input;
}

由于您使用指针作为类成员,因此您需要编写自己的复制和移动语义,以使其正常工作。

这是使用类似的功能

CustomStringClass a;
CustomStringClass b = a;
CustomStringClass c(b);
///etc

有很多关于移动语义的好帖子和视频。 选择一个和你有共鸣的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM