Store member variables on heap or stack when extending QMainWindow? - c++

I have a program (written in c++ using Qt) which shows an image in a window and takes measurements and draws to the image. All of the Qt tutorials use the heap to store user interface objects so I have done the same.
When I extend the QMainWindow class, I add a number of member variables which I use to store measurements and different versions of the image. I do not explicitly store these on the heap (no new identifier), but my understanding is if the class is defined on the heap, then so are its members.
Questions:
If the class instance is defined with new
Should the UI elements be pointers and defined with 'new' or should they just be variables and used right away? (Perhaps because UI objects can be created with parents, this makes cleanup easy.)
If they should be assigned with new in the above question, should all member variables (measurements and images) also be used with new and then deleted?
Hopefully my vocabulary is correct.

It does not matter whether UI objects will be allocated dynamically, or reside on the stack (yes, if the whole object is allocated on the heap, so are its members, but again, it does not matter whether they're pointers or not - on the other hand, performance might be worse with pointers - additional space, allocation).
In both cases, you don't have to care about resource management. That however, is not the case with your own types not deriving from QObject and not having the window as a parent. You want to avoid raw or smart pointers, where you don't need them.

Related

gtkmm: what is Glib::RefPtr usecases?

I am writing a little GTK3 app with C++ and gtkmm library.
In the gtkmm documentation usually some concrete instances such as Gtk::Application, Gtk::Builder, Gtk::StatusIcon etc. initialized with create() static methods that return a Glib::RefPtr. Meanwhile child widgets usually arise just on stack.
That is not clear for me:
Is it because memory stack usage or something else? There is no RefPtr's in my code for now. I checked usage of stack with valgrind's massif tool, peak usage was about 100 KB. Seems not too low for me, but comparable size example with RefPtr's takes a same piece of stack memory.
May I place all instances just on stack like Application myapp, or should I always use create() while it present?
What advantages the pointers provide in this case?
Glib::RefPtr is a reference-counted smart pointer that predates std::shared_ptr and performs the same essential functions. The use case for it is similar -- it allows multiple objects want to share ownership of an object without knowing about each other directly.
In your specific examples, an icon might be shared because it is used in multiple places in a UI, and you don't want to maintain many copies of the same image data, which could use a considerable bit of memory if there are many icons.
The Application and Builder objects are likely held by multiple objects in your program (e.g., different window or dialog objects), so the reference counting keeps each alive as long as one of those objects is still using it. This frees these users of the Application object from having to know about all the other parts of the program that might use the shared Application object. When one window is done with the Application, it destroys its smart pointer to the Application. If that window was the last owner, this also destroys the Application object, but otherwise it stays alive for the other users -- all without your destroyed window knowing about it whether the Application lives on or not.
Is it because memory stack usage or something else? There is no RefPtr's in my code for now. I checked usage of stack with valgrind's
massif tool, peak usage was about 100 KB. Seems not too low for me,
but comparable size [example with RefPtr's][1] takes a same piece of
stack memory.
The main reason is that gtkmm is a thin C++ wrapper over Gtk+ library written in C. Most objects in Gtk+ are allocated on heap (eg. GtkApplication object is created using gtk_application_new function), and are reference counted (manually, using g_object_ref/g_object_unref functions). In other words, those objects have already shared pointer semantics, albeit expressed in plain C. Because of this, it makes most sense to represent those objects in C++ as smart pointers - Glib::RefPtr in this case.
May I place all instances just on stack like Application myapp, or should I always use create() while it present?
No, because Gtk::Application contructors are protected, so compiler won't allow to create those objects on stack.
What advantages the pointers provide in this case?
I think it's the other way round. Keeping those objects on stack wouldn't provide any advantages, as Gtk objects wrapped by gtkmm objects are essentially shared pointers.

C++ Library free pointer

I am creating a simple C++ MIDI library and I ran into a small problem. Currently, I have implemented everything but the reading of files. Internally, I have a std::vector with raw, dynamically allocated pointers (with the new() keyword) of events, which is an abstract class and can therefore not be instantiated. Now that I've finally started on the reading part, there is a slight problem. I will have to allocate the objects myself and later free them too. This creates problems though, since the user of the library may include events in between or append them. This will mean that there are dynamic pointers that have been created elsewhere in my std::vector, which makes freeing a difficult question.
To make this question more general, I was wondering what I should do with pointers provided by the user of the library. What should I do with them? I was thinking one of the points on the list:
Free all pointers and note that pointers given to the class do not have to be freed any more (which seems strange and counter-intuitive, since the new is matched with the delete in a completely different setting)
Maintain a list of pointers provided by the user and simply skip any pointer in that list (probably not really a solution, because the entire list would have to be checked every time)
Making the creation of events only available with the class, so the user cannot create pointers with the new keyword but only by letting the handling class allocate them.
Forcing the use of shared pointers and using them exclusively in my code, so that they will be automatically freed when they go out of scope.
Maintaining a list of your own pointers and only freeing them, and let the user given pointers go out of scope / they will have to clean them up themselves.
...? (something I have maybe not thought of?)
So please, tell me what is customary in a situation like this, where the user of the library provides pointers which is added to a list maintained by you and then the list goes out of scope, while you have your own pointers mixed with theirs.
Thanks in advance!
Pick a consistent policy. Don't choose any of those options that lead to you have to destroy some objects in some places and other objects in other places. Especially not those approaches in which the user is responsible for destroying some objects but not others. Ownership should be handled uniformly.
My first suggestion would be to avoid dynamically allocating objects completely. Can you not store a std::vector<Event> and pass Events by value to and from your library? Then the user can happily not care about the ownership of objects, but they can choose to dynamically allocate them if they wish.
If you really need to dynamically allocate objects, I suggest that you always wrap them in smart pointers so that ownership is managed automatically. If, for example, you are allocating some object on behalf of the user, the standard interface for this is something like:
std::unique_ptr<Object> createObject();
If, on the other hand, your library has some internal dynamically allocated that it needs to share with the user, return a std::shared_ptr.

When do I use pointers in Qt?

Ive been programming Qt for a while now and I am wondering what the difference is between these two cases:
case1:
header:
QPushButton * button;
source file:
button = new QPushButton(this);
button->setText("Button");
button->resize(100,100);
and
case2:
header:
QPushButton button;
source:
button.setParent(this);
button.setText("Button");
button.resize(100,100);
Both produce a button, but when should I use the former and when the latter case? And what is the difference between the two?
The difference between the first and second case is that when you use pointers and the new statement to allocate the button, the memory for the button is allocated in the free store (heap). In the second statement the memory is allocated on the stack.
There are two reasons why you would rather allocate memory in the free store than the stack.
The stack is of limited size and if you blow your stack budget your program will crash with a stack overflow. One can allocate much more memory in the free store and if a memory allocation fails, all that normally happens is that a bad_alloc exception is thrown.
Allocation on the stack is strictly last in first out (LIFO) which means that your button cannot exist for longer than the code block (whats between the {...} ) that allocated the memory. When memory is allocated in the free store, you as the programmer have full control of the time that the memory remains valid (although carelessness can cause memory leaks)
In your case, if the button just needs to exist for the duration of the calling function, you will probably be ok allocating the button on the stack; if the button needs to be valid for much longer stick to the free store
Qt memory management works with hierarchies of objects, when parent object deletes child objects automatically on destroying. This is why Qt programs always use pointers in similar cases.
Memory Management with Qt:
Qt maintains hierarchies of objects. For widgets (visible elements) these hierarchies represent the stacking order of the widgets themselves, for non-widgets they merely express "ownership" of objects. Qt deletes child objects together with their parent object.
In the first case you are dynamically allocating the button (which means that it will be destroyed when the parent is destroyed). In the second case the button will disappear when the code block ends (meaning it goes out of scope).
Use the first when you want to QObject, you are referring to, to last more than just the block in which it is created.
In the context of the class you are referring to (assuming the button is a member variable in both cases) it doesn't make much difference.
Also you may want to use pointers when using polymorphism.
An useful specific usage: when posting custom events, carrying detailed data, for instance:
/** support SWI... prolog_edit:edit_source(File) */
struct reqEditSource : public QEvent {
QString file;
QByteArray geometry;
reqEditSource(QString file, QByteArray geometry = QByteArray())
: QEvent(Type(User+1)), file(file), geometry(geometry) {}
};
you can 'fire and forget' them:
qApp->postEvent(this, new reqEditSource(files[i], p.value(k).toByteArray()));
The event will be deleted after its delivery.
Many functions in Qt that take an object as argument, actually take a pointer to an object. That's because passing an object "by value" would actually create a copy of the object (via copy constructor) and pass that copy! Creating a new copy of the object has a lot of overhead. At the same time, passing the object "by reference", i.e. as a pointer, will just pass a 32-Bit memory address, which is a very lightweight operation.

When and why to declare member variables on the heap C++

Ok, so I'm very new at C++ programming, and I've been looking around for a couple days for a decisive answer for this. WHEN should I declare member variables on the heap vs. the stack? Most of the answers that I've found have dealt with other issues, but I want to know when it is best to use the heap for member variables and why it is better to heap the members instead of stacking them.
There are two important concepts to grasp first:
One should avoid thinking in terms of "heap" and "stack". Those are implementation details of your compiler/platform, not of the language.1 Instead, think in terms of object lifetimes: should the object's lifetime correspond to that of its "parent", or should it outlive it? If you need the latter, then you'll need to use new (directly or indirectly) to dynamically allocate an object.
Member variables always have the same lifetime as their parent. The member variable may be a pointer, and the object it points to may well have an independent lifetime. But the pointed-to object is not a member variable.
However, there is no general answer to your question. Crudely speaking, don't dynamically allocate unless there is a good reason to. As I hinted above, these reasons usually correspond to situations where the lifetime needs to differ from its "parent".
1. Indeed, the C++ standard doesn't really talk about "heap" and "stack". They're important to consider when optimising or generally thinking about performance, but they're mostly irrelevant from a program-functionality point of view.
Member variables are members of the class itself. They are neither on
the heap nor on the stack, or rather, they are where ever the class
itself is.
There are very few reasons to add a level of indirection, and allocate a
member separately on the heap: polymorphism (if the type of the member
is not always the same) is by far the most common.
To get some terminology straight: What you call a heap and stack describe the lifetime of objects. The first means that the lifetime is dynamic, the second automatic and the third (which you don't mention) is static.
Usually you will need dynamic lifetime of an object when it should outlive the scope it was created in. Another common case is when you want it to be shared across different parent objects. Also, dynamic lifetime is also necessary when you work with a design that is heavyly object-oriented (uses a lot of polymorphism, doesn't use values), e.g. Qt.
An idiom that requires dynamic lifetimes is the pimpl-idiom.
Most generic-programming libraries are more focused towards value and value-semantics, so you won't use dynamic binding that much and automatic lifetimes become a lot more common.
There are also some examples where dynamic allocation is required for more implementation specific reasons:
dynamically sized objects (containers)
handling incomplete types (see pimpl-idiom)
easy nullability of a type
All of those are just general guidelines and it has to be decided on a case by case basis. In general, prefer automatic objects over dynamic ones.
The stack refers to the call stack. Function calls, return addresses, parameters, and local variables are kept on the call stack. You use stack memory whenever you pass a parameter or create a local variable. The stack has only temporary storage. Once the current function goes out of scope, you no longer have access to any variables for parameters.
The heap is a large pool of memory used for dynamic allocation. When you use the new operator to allocate memory, this memory is assigned from the heap. You want to allocate heap memory when you are creating objects that you don't want to lose after the current function terminates (loses scope). Objects are stored in the heap until the space is deallocated with delete or free().
Consider this example:
You implement a linked list which has a field member head of class node.
Each node has a field member next. If this member of the type Node and not Node* the size of every Node would depend on the number of the nodes after it in the chain.
For example, if you have 100 nodes in your list your head member will be huge. Because it holds the next node inside itself so it needs to have enough size to hold it and next holds the next and so on. So the head has to have enough space to hold in it 99 nodes the next 98 and so on...
You want to avoid that so in this case it's better to have pointer to to next node in each Node rather than the next node itself.

Use of dynamic memory allocation for a client socket class in C++

Coming from a Java background I am still grappling with C++ memory allocation and when to use smart pointer, automatic stack allocation or dynamic stack allocation.
However I have a concrete use case:
I created a class which consists only of a client socket and a function which sends a std::string to the target machine and closes the connection at the end.
I use this client class in several functions. The functions where I use the client class are triggered by certain events. Therefore every event notification is sent via socket.
My question is, should I use automatic stack allocation here? My guess is yes, as I don't need dynamic allocation. If this is true, under what circumstances would a client class be in the position to be allocated dynamically or when would it be useful?
Given that a socket/file descriptor is really just an int handle on an object managed by the OS, I'd go for stack allocation + copy construction or pass-by-reference whenever possible. You're only copying an int and the relative overhead of indirection through a pointer would be great.
(If you're also storing the hostname and some other stuff, consider using a shared pointer.)
I'd allocate on the stack only if the lifetime of the allocated object is tightly bound to the procedural scope.
If you ever need to pass references around that might (need to) be kept after the function returns, you need to dynamically allocate it.
Of course in C++ the point quickly becomes moot for the actual storage volumes, since e.g. STL containers (vector, list, map et friends) do their element allocations dynamically anyway [1]
So it really is about lifetimes.
I find myself managing lifetimes by class-responsability rather than function scope[1]. I regularly end up with a single Application (class) instance containing all 'global' objects, each containing their objects etc. The application object can be a static global, or just a stack alloc-ed local variable in main - it doesn't matter much as long as you don't declare a const char [300][400] member in it :)
$0.02
[1] that is: in the absense of a particularly mischievous custom allocator which you are probably not interested in at the moment :)
[2] With closures, function scope can get eerily close to class responsability - in the same way that functional languages use closures to mimic OOP patternss