C++ Logo


Advanced search

Re: Ptr proposal: looking for feedback

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sat, 18 Jul 2020 16:18:22 -0400
On Sat, Jul 18, 2020 at 3:51 PM Jefferson Carpenter via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> On 7/18/2020 3:10 PM, Jason McKesson via Std-Proposals wrote:
> > On Thu, Jul 16, 2020 at 6:32 PM Jefferson Carpenter via Std-Proposals
> > <std-proposals_at_[hidden]> wrote:
> > The C++ standard library should not promote bad programming practices,
> > and it should avoid having types that actively encourage them.
> >
> > The fundamental problem with what you call "context-dependent
> > ownership" is that it makes code hard to reason about. A particular
> > piece of code can never *in isolation* be deemed "reasonably memory
> > safe"; it can only be "memory safe" within a specific context. A
> > context that cannot be verified statically; it can only be verified
> > dynamically, at runtime.
> >
> > If a function takes a `unique_ptr` by value and it stores it in an
> > object, there's no need to think about it further. There's no need to
> > write tests for what happens if you use the object after the pointer
> > is deleted because you *cannot do that*.
> >
> > Any similar function which takes a `ptr` by value now has to have a
> > bunch of tests written for it to see what happens if you play around
> > with when the object it points to gets destroyed. That represents
> > higher maintenance costs.
> "gets destroyed" when? If you're referring to its being destroyed
> /during/ the function call, then that is only possible if the function
> destroys it or std::moves it into another function call.

You may have missed a crucial part of the example. It was specifically
about a function that *stores* the pointer in an object (perhaps the
function is that object's constructor). The expectation in the
`unique_ptr` case is that the object now owns that resource. The
expectation in the `ptr` case is... what? Maybe the object owns it,
maybe it doesn't? So how do you now test the behavior of the object
after this function's execution?

After all, the object stored that `ptr` so that it can use it. Which
functions on that object are expected to be valid in the event of a
dangling pointer and which aren't?

If you're in the realm of pure functions with immutable state, maybe
this type makes sense. But in the real world, where state is changed
frequently and resources are owned by more than just stack variables,
this just isn't tenable as a general-purpose tool.

Received on 2020-07-18 15:21:48