With the first method, QHttp _http, you are creating the object on the stack, and it will be there as long as the class is around. For objects of significant size that can be very inefficient, memory-wise, as stack memory is limited.
But luckily there is more abundant heap memory you can use, and C++ has pointers, which are variables that point to objects created on the heap.
So normally for objects of significant size, if you need them to have class scope, you create the object on the heap with "new," and store a pointer variable to that object in the class, instead of storing the object itself, because its more efficient. Consider this code:
cout << sizeof(p_http) << endl;
cout << sizeof(http) << endl;
QHttp * p_http = new QHttp();
QHttp http;
cout << sizeof(p_http) << endl;
cout << sizeof(http) << endl;
To copy to clipboard, switch view to plain text mode
Output:
4
8
Not a huge difference in this situation, but GUI objects are a much different story. For example:
cout << sizeof(p_widget) << endl;
cout << sizeof(widget) << endl;
QWidget * p_widget = new QWidget();
QWidget widget;
cout << sizeof(p_widget) << endl;
cout << sizeof(widget) << endl;
To copy to clipboard, switch view to plain text mode
Output:
4
20
Something to keep in mind, a pointer variable is not the object. It is only a variable that stores the memory address of an object - about the size of an int. When you use the -> (called the dereference arrow) on the pointer, you are essentially saying "give me the object you are pointing to." That is why you can then use the methods contained in the object.
Hope that helps...
Bookmarks