簡體   English   中英

如何執行char *的深層復制?

[英]How to perform a deep copy of a char *?

我對如何執行char *的深拷貝a感到有些困惑。 這就是我所擁有的:

Appointment(Appointment& a)
{
  subject = new char;
  *subject = *(a.subject);
}

Appointment(Appointment& b)
{
  location = new char;
  *location = *(b.location);
}

char *subject;
char *location;

我正在嘗試對char指針的主題和位置進行深層復制。 這樣行嗎? 如果不是,那么有關如何執行此操作的任何建議?

您可以使用strdup 由於它在內部使用malloc請不要忘記在析構函數中調用free

看到:

由於您使用的是C ++,因此應使用std::string滿足您的字符串需求。

您編寫的以下代碼

Appointment(Appointment& a)
{
  subject = new char;
  *subject = *(a.subject);
}

不會做您想做的事,在上面分配一個字符( new char ),然后將a.subject的第一個字符分配給它( *subject = *(a.subject)

為了復制char*指向的字符串,您必須首先確定字符串長度,分配內存以容納該字符串,然后復制字符。

Appointment(Appointment& a)
{
  size_t len = strlen(a.subject)+1;
  subject = new char [len]; // allocate for string and ending \0
  strcpy_s(subject,len,a.subject);
}

char*的另一種方法是使用std::vector<char> ,這取決於您要對字符串執行的操作。

您必須跟蹤char*長度才能復制它們,例如:

class Appointment
{
public:
    char *subject;
    int subject_len;

    char *location;
    int location_len;

    Appointment() :
        subject(NULL), subject_len(0),
        location(NULL), location_len(0)
    {
    }

    ~Appointment()
    {
        delete[] subject;
        delete[] location;
    }

    Appointment(const Appointment& src) :
        subject(new char[src.subject_len]), subject_len(src.subject_len),
        location(new char[src.location_len]), location_len(src.location_len)
    {
        std::copy(src.subject, src.subject + src.subject_len, subject);
        std::copy(src.location, src.location + src.location_len, location);
    }

    Appointment& operator=(const Appointment& lhs)
    {
        delete[] subject;
        subject = NULL;

        delete[] location;
        location = NULL;

        subject = new char[lhs.subject_len];
        subject_len = lhs.subject_len;
        std::copy(lhs.subject, lhs.subject + lhs.subject_len, subject);

        location = new char[lhs.location_len];
        location_len = lhs.location_len;
        std::copy(lhs.location, lhs.location + lhs.location_len, location);
    }
};

在這種情況下,最好使用std::string代替:

class Appointment
{
public:
    std::string subject;
    std::string location;

    Appointment()
    {
    }

    Appointment(const Appointment& src) :
        subject(src.subject), location(src.location)
    {
    }

    Appointment& operator=(const Appointment& lhs)
    {
        subject = lhs.subject;
        location = lhs.location;
    }
};

這可以進一步簡化,因為由編譯器生成的默認構造函數和賦值運算符足以自動為您深度復制值:

class Appointment
{
public:
    std::string subject;
    std::string location;
};

沒有。

您需要分配足夠的內存來存儲要復制的字符串

subject = new char [strlen(a.subject + 1]; // +1 to allow for null charcter terminating the string.

然后使用strncpy memcpy或在循環中復制所有字符以復制字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM