簡體   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