[Interest] more QSharedPointerQuestions

Bo Thorsen bo at fioniasoftware.dk
Fri Mar 2 19:33:09 CET 2012


Den 02-03-2012 14:07, Jason H skrev:
> You raise some good points. In truth, I was told to use QSharedPointer,
> but I had some of the same points you did. His intention (as I
> understand it) was to use QSharedPointer to stop accidental deletes.

I know some will disagree with this, but anyway...

Most times people use a shared pointer is because they are coding 
without complete control over memory handling. No C++ implementation of 
a shared pointer can fix two that point to each other. The real problem 
is fixed when you know and control all new and delete.

In some cases, this is an elitist POV, but with the QObject parent child 
relationship, it's not. You *don't* want shared pointers to screw up 
your memory trees.

There are cases (like asio code with boost) where shared pointers are 
the proper solution, and sometimes I use them as well. But assuming the 
use of shared pointers magically fixes memory issues in the application 
is a flawed way of thinking.

But my main problem with using shared pointers is that it's often used 
as an excuse to avoid answering "who owns this object". Assign 
responsibilities of ownership, and most times it becomes clear who 
should delete objects. In the few cases where this is not the case, 
shared pointers can be a valid solution.

A lot of quality time with valgrind will be a much better way to learn 
how to do quality code that doesn't have memory issues.

Bo Thorsen,
Fionia Software.

-- 

Expert Qt and C++ developer for hire
Contact me if you need expert Qt help
http://www.fioniasoftware.dk



More information about the Interest mailing list