[英]How to copy a char* to another char* and free the 1st without affecting the 2nd
My code is below.我的代码如下。 Initially it showed an error that a same memory location is being freed twice.ie Returned object temp is freed twice(while return and after copied to obj2).
最初它显示了一个错误,即相同的内存位置被释放了两次。即返回的对象 temp 被释放了两次(在返回和复制到 obj2 之后)。 So, i overloaded the copy constructor to have different memory while coping.
因此,我重载了复制构造函数以在应对时拥有不同的内存。 Then error disappeared but a garbage value was stored in obj2 instead of "ll".
然后错误消失了,但垃圾值存储在 obj2 而不是“ll”中。 Then I overloaded the = operator void main line 2 from shallow to deep copy.
然后我将 = 运算符 void 主线 2 从浅拷贝重载到深拷贝。 Now garbage value is gone but it has a null value instead of "ll".I don't want to comment free() or use any functions from #include.Can someone say what should do?.
现在垃圾值消失了,但它有一个空值而不是“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);
}
You need to allocate new memory and shift it to use a raw char array of unknown length.您需要分配新内存并将其转换为使用长度未知的原始 char 数组。
Also it's a common recommendation not to use "using namespace std", and a personal recommendation to use the same name for function arguments and member function, having to remember to use this-> correctly is just asking for trouble.此外,通常建议不要使用“使用命名空间 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;
}
Since you are using a pointer as a class member, you need to write your own copy and move semantics, for that to work correctly.由于您使用指针作为类成员,因此您需要编写自己的复制和移动语义,以使其正常工作。
This is to use functions like这是使用类似的功能
CustomStringClass a;
CustomStringClass b = a;
CustomStringClass c(b);
///etc
There's a lot of good posts and videos on move semantics.有很多关于移动语义的好帖子和视频。 Pick one that vibes with you.
选择一个和你有共鸣的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.