c++内存泄漏与否

发布于 2025-01-04 01:31:12 字数 570 浏览 0 评论 0原文

我有代码:

class foo
{
public:
  bar(const QString& s){}
.....
};

int main()
{
 .....
 foo f;
 for(int i = 0; i < 100; i++)
     f.bar(QString("%1").arg(i));
 ....
 return 0;
}

我在字符串“f(QString("some string text?"));”上有内存泄漏或不?

另一个例子,

class foo
{
  QUdpSocket socket;
public:
  foo();  
  void send_msq();
};

foo::foo(){
  socket.bind(QHostAddress("192.168.20.1"),50501);
}

void send_msq()
{
  socket.writeDatagram(...);
}

我对字符串“socket.bind(QHostAddress(“192.168.20.1”),50501);”有任何问题?

i have code:

class foo
{
public:
  bar(const QString& s){}
.....
};

int main()
{
 .....
 foo f;
 for(int i = 0; i < 100; i++)
     f.bar(QString("%1").arg(i));
 ....
 return 0;
}

I have memory leak on string "f(QString("some string text?"));" or not?

Another example

class foo
{
  QUdpSocket socket;
public:
  foo();  
  void send_msq();
};

foo::foo(){
  socket.bind(QHostAddress("192.168.20.1"),50501);
}

void send_msq()
{
  socket.writeDatagram(...);
}

I have any problem on string "socket.bind(QHostAddress("192.168.20.1"),50501);" ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

做个少女永远怀春 2025-01-11 01:31:12

不存在内存泄漏。 QString 类管理自己的内存(假设您正在谈论这个 QString

您正在创建该类的临时对象,当对 foo::bar 的调用返回时,该临时对象将被销毁。析构函数运行,释放所有内存 一般来说,只要你的资源是由类

管理的,并且你没有用new分配它们,你就不需要担心。释放资源,因为当类实例超出范围时,析构函数将运行当

您使用 new 或使用其生命周期不由类管理的资源(如 malloc 返回的内存)时 。 或返回的文件fopen (与 fstream 相反,它是一个类,在销毁时会进行清理)),这就是您需要确保清理它的

最佳方法 。顺便说一句,要做到这一点,就是将此类资源包装在一个类中,该类通过构造函数和析构函数管理资源的生命周期,然后使用该类而不是“原始”资源;这称为资源获取即初始化模式。

There is no memory leak. The QString class manages its own memory (assuming you are talking about this QString.

You are creating a temporary of that class, which is destroyed when the call to foo::bar returns. At that point, the destructor is run, freeing any memory held by the QString class.

In general, as long as your resources are managed by classes, and you are not allocating them with new, you don't need to worry about freeing resources, as the destructor will run when the class instance goes out of scope.

When you use new, or use resource whose lifetime isn't managed by a class (like memory returned by malloc or a file returned by fopen (as opposed to fstream, which is a class and cleans up when it is destroyed)), that's when you need to make sure to clean it up.

The best way to do that, incidentally, is to wrap such resources in a class that manages the resource's lifetime through the constructor and destructor, and then use that class instead of the "raw" resource; this is known as the Resource Acquisition Is Initialization pattern.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文