如何执行char *的深度拷贝
How to perform a deep copy of a char *?
我对如何执行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
或复制循环中的所有字符来复制字符串
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- OpenGL在启用深度测试时不会丢弃我的碎片
- 如何在没有数据拷贝的情况下从指针创建一个Eigen VectorXd对象
- C++尝试深度复制唯一指针时出现内存访问冲突
- 试图找到二叉树的深度
- 与浅拷贝构造函数和深拷贝构造函数混淆
- 操纵安卓相机的深度图导致应用程序崩溃
- 深度值没有意义 R200 相机
- 对如何制作双链表的深度副本感到困惑?
- 以C++访问 HoloLens 2 深度图像
- 在 c++ 中使用深度复制的运算符重载
- 使用复制构造函数修复浅拷贝
- 指向指向对象的指针数组的指针的深度拷贝
- 如何执行char *的深度拷贝
- Poco::JSON::Object的深度拷贝
- c++深度拷贝中的内存泄漏
- 链表的深度拷贝
- 一个结构体的深度拷贝,它嵌入了许多简单的变量和一个嵌套结构体
- 如何创建一个QList的深度拷贝(Qt 4.8)
- 多线程深度拷贝