c++内存泄漏与否
我有代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不存在内存泄漏。
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 thisQString
.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 theQString
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 bymalloc
or a file returned byfopen
(as opposed tofstream
, 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.