在哪里释放在重载运算符的函数中分配的内存
我试图学习基本的 C++ 运算符重载概念。我有一个 mystring 类和相关代码,如下所示。在用于重载“+”运算符的函数中,我可以在哪里释放内存以避免内存泄漏。
#include <iostream>
class mystring
{
char *ptr;
public:
mystring(char *str = "")
{
ptr = new char[strlen(str) + 1]
strcpy(ptr,str);
}
mystring operator +(mystring s)
{
char *str = new char[strlen(ptr) + strlen(s.ptr) + 1];//where should this memory be freed
strcpy(str,ptr);
strcat(str,s.ptr);
return mystring v1(str);
}
~mystring()
{
delete [] ptr;
}
};
int main()
{
mystring a="Hello",b="World",c;
c = a + b;
}
I was trying to learn basic C++ operator overloading concepts. I have a class mystring and related code as shown below. In functions used to overload '+' operator, where can I free the memory to avoid memory leaks.
#include <iostream>
class mystring
{
char *ptr;
public:
mystring(char *str = "")
{
ptr = new char[strlen(str) + 1]
strcpy(ptr,str);
}
mystring operator +(mystring s)
{
char *str = new char[strlen(ptr) + strlen(s.ptr) + 1];//where should this memory be freed
strcpy(str,ptr);
strcat(str,s.ptr);
return mystring v1(str);
}
~mystring()
{
delete [] ptr;
}
};
int main()
{
mystring a="Hello",b="World",c;
c = a + b;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单修复:
一个私有构造函数
或者有
Simple fix:
Or have a private constructor
then
您的串联运算符将遇到与赋值运算符相同的问题,因此这将是一本有用的读物: http://www.parashift.com/c++-faq-lite/assignment-operators.html
Your concatenation operator is going to have the same problems as assignment operators so this will be a useful read: http://www.parashift.com/c++-faq-lite/assignment-operators.html
内存应该在 mystring 的析构函数中释放,但您需要重新考虑一下您的设计。
请注意,您需要一个默认构造函数来创建空字符串。此外,您还必须处理 ptr 资源,添加适当的复制构造函数、赋值运算符和析构函数。除此之外,您应该通过 const& 获取参数。此外,+ 运算符最好作为自由函数来实现;作为朋友或基于成员 += 运算符。
Memory should be freed in the destructor of mystring, but you will need to rethink your design a bit.
Note you need a default constructor to create an empty string. Besides you will have to handle the ptr resource adding a proper copy-constructor, an assignment operator and a destructor. Besides that, you should be taking your parameter by const&. Furthermore, the + operator is better implemented as a free function; either as a friend or based in a member += operator.
我明白练习的目的只是为了学习。我会避免在现实生活中创建这样的字符串类型。现在回到最初的问题,解决方案是始终使用 RAII 来管理资源,这可以通过不同的方式完成,但最简单的方法之一是一起使用复制和交换 三法则(我几天前写过此处 使用 RAII 来管理资源意味着始终意味着您无需过多考虑如何以及何时必须释放它们。
I understand that the point of the exercise is just to learn. I would avoid creating a string type like this in real life. Now back to the original problem, the solution is to always use RAII for management of resources, and that can be done in different ways, but one of the simplest one is using the copy-and-swap together with the rule of the three (I wrote about that just a couple of days ago here Using RAII to manage the resources means at all times means that you do not need think too hard on how and when you have to release them.