[Development] The future of smart pointers in Qt API

Scott Bloom scott at towel42.com
Tue Feb 4 00:53:57 CET 2020


From: Development [mailto:development-bounces at qt-project.org] On Behalf Of André Pönitz
Sent: Monday, February 3, 2020 3:50 PM
To: Giuseppe D'Angelo <giuseppe.dangelo at kdab.com>
Cc: development at qt-project.org
Subject: Re: [Development] The future of smart pointers in Qt API

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'
-----------------------
To be fair, while I 100% agree with the reasons given, you are not listing one of the (only???) reasons, that a smart pointer shared or unique, are truly necessary.

When you are working with the possibility that the lifetime of the pointer, might not be exception safe.   

Scott


More information about the Development mailing list