Cannot create QImage using smart pointers
-
Can you explain exactly how many QImage do you need to generate ?
-
Christian Ehrlicher Lifetime Qt Championreplied to chessking5544 on last edited by Christian Ehrlicher
@chessking5544 said in Cannot create QImage using smart pointers:
I'm looking for a way to get auto deletion for all QImages created.
Don't create it on the stack but on the heap.Don't create it on the heap but on the stack. QImage will allocate it's internal image data on the stack anyway./edit: mixed up stack and heap for unknown reasons - fixed :)
-
As @Christian-Ehrlicher suggests: no need for heap allocation in the case of QImage. That will also free you from having to delete them manually.
-
ok. thanks
-
@Christian-Ehrlicher said in Cannot create QImage using smart pointers:
Don't create it on the stack but on the heap.
Do you want to rephrase this? :)
-
@JonB said in Cannot create QImage using smart pointers:
Do you want to rephrase this? :)
What should be rephrased here? It's basic ++ stuff. You can create an object either on the heap with new or directly on the stack.
-
@Christian-Ehrlicher "Don't create it on the stack but on the heap." - you should exchange stack and heap :-)
-
@jsulm Thx, fixed
-
@chessking5544 said in Cannot create QImage using smart pointers:
Will c++ smart pointers work, or is there just no way to do this?
Just for completeness I will answer this. But first I have to agree with the others that you should allocate QImage on the stack. Good C++ style avoids pointers wherever possible. The best lifetime management is variables on the stack. Containers - and in this case I will count QImage as a container - will internally allocate memory on the heap. This is a good thing as your stack is quite small. I don't know C# well (but assume it has some similarity to Java within this respect), but objects do not need to be allocated using
new
in C++. If you want polymorphism you can use references instead of pointers. Rarely do you actually need pointers in C++.Now to the answer: C++ smart pointers work with every class. Just use it like this:
std::shared_ptr<QImage> image = std::make_shared<QImage>(QSize(1920,1080), QImage::Format_RGB32);
Note the use of
make_shared
here. This will automatically handle out-of-memory errors. Internally it will callnew
and hand down its parameters to the constructor of QImage. It is advised to usemake_shared<QImage>(...)
overshared_ptr<QImage>(new QImage(...))
(I can't remember all the reasons).