[Development] The future of smart pointers in Qt API

André Pönitz apoenitz at t-online.de
Tue Feb 4 00:49:31 CET 2020


On Mon, Feb 03, 2020 at 10:25:40PM +0100, Giuseppe D'Angelo via Development wrote:
> I've asked "what's wrong with the C++ smart pointers" a dozen times and
> never received a satisfactory answer.

Did you? I am - to some degree truly - afraid I didn't notice.

Answer would have been easy: They solve problems that should not occur
on a large scale in a sensible setup.

To start with: I was not much in favour of std::auto_ptr when it was
standardized. People started hyping it, best thing since sliced bread.
Sprinkle your code base with it or you are doomed.

Well. Fast forward twenty years. Case settled.

boost::shared_ptr, ..., std::unique_ptr: Same story, just not finished:

An actual "need" for a shared pointer is typically a sign that ownership
is not clear at all: "Here's a thing, it doesn't really belong anywhere,
so let's copy it around, last one switches off the light". Fixed by making
ownership clear. Also solves the problem of needing to copy some stuff
because it's not copied, just referenced. And sure, there *are* situation
where shared pointers are useful, and it's of course fine to use them
if there's such reason.

An actual "need" for a unique pointer is typically a sign that things
are created, passed around until they end up somwhere, for a long time
so that people get unsure about ownership or have developed an
irrational fear of naked pointers.  Fixed by not having the 'factory'
create the object and pass the object around, but by passing the factory
around (by 'reference') and letting the receiver create the object.
Additional advantage: creation can take input both from the factory
setup (say, lambda capture) and the receiver side, saving potentially a lot
of state. And it's of course fine to use unique pointers if that's not
the reason. E.g. to delete dynamic stuff in case of early returns. I.e.
a kind of, surprise, "scoped" pointer.

That people coming from Java exhibit a high affinity to shared pointers
is not exactly news in this millenium. A bit more amusing is that some
proponents of "modern" C++ demand using unique pointers, when actually
more direct, less boiler-plate requiring tools (lambdas...) were 
standardized at the same time.

Andre'



More information about the Development mailing list