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);” ?
There is no memory leak. The
QStringclass 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::barreturns. At that point, the destructor is run, freeing any memory held by theQStringclass.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 bymallocor 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.