如何执行char *的深度拷贝

How to perform a deep copy of a char *?

本文关键字:深度 拷贝 char 何执行 执行      更新时间:2023-10-16

我对如何执行char *的深度复制有点困惑。这是我的文件:

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

我试图执行字符指针主题和位置的深度拷贝。这能行吗?如果没有,有什么建议吗?

由于您使用的是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 
  strcpy_s(subject,len,a.subject);
}

char*的另一种替代方法是使用std::vector<char>,这取决于您想对字符串做什么。

您可以使用strdup。因为它在内部使用malloc,所以不要忘记在析构函数中调用free

:

  • 第6行的手册
  • 函数- strdup() -它在C中做什么?-栈溢出

您必须跟踪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;
};

no.

你需要分配足够的内存来存储你想要复制的字符串

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

然后使用strncpy memcpy或复制循环中的所有字符来复制字符串