r/cpp • u/pedersenk • Nov 21 '21
Reasoning behind a lack of std::weak_ptr<T>::operator->()
Hi there,
I have always been interested in the decision behind the need of a lock() call on a std::weak_ptr<T>. Generally in my travels, the main reason I have come across is to guarantee the lifespan of the owned data during access. However, surely something like this would solve that:
shared_ptr<T> weak_ptr<T>::operator->()
{
return lock();
}I am going to assume that the standards committee knows and understands the operator-> drill-down behavior quite well. So the following usage would be very possible:
std::shared_ptr<Employee> emp = std::make_shared<Employee>();
std::weak_ptr<Employee> emp2 = emp;
emp->calculateWage();
emp2->calculateWage();This should only cause the same overhead as a lock() call too. Not only this but it should provide an even safer guarantee that the data won't be deleted during access because you have created a temporary std::shared_ptr<T> copy which you have no access to (i.e impossible to reset) during the dereference.
Obviously this would be easier than providing an operator* due to the drill-down functionality. Is a lack of -> purely to stay consistent with this?
Any ideas / suggestions would be very appreciated!
Edit: Many thanks for the discussion so far. It seems like enforcing a shared_ptr to be provided is for a developer to explicitly check before access rather than simply ptr.lock()->testFunc().
Edit 2: Thanks again all for the discussion. It was interesting to hear about some potential issues my solution would overlook. It was particularly interesting to see some of the issues present in a large project providing a weak_ptr operator->.
Edit 3: So just as an addition; I believe the following should be safe (including for multithreaded environments). However there is some overhead that may not be acceptable:
shared_ptr<T> weak_ptr<T>::operator->()
{
std::shared_ptr<T> rtn = lock();
if(!rtn)
{
throw std::bad_weak_ptr();
}
return rtn;
}20
u/27Shua27 Nov 21 '21
With a weak_ptr, you never know whether or not the shared_ptr is yet expired. The pattern should always be:
auto shared(weakPtr.lock());
if (shared != nullptr){
// Here we can use shared safely
}I don't see a practical way to build that into the standard library. Maybe something like
shared_ptr<T> weak_ptr<T>::operator->()
{
auto shared(this->lock());
if (shared == nullptr)
throw std::bad_weak_ptr();
return shared;
}2
u/pedersenk Nov 21 '21
I would have thought an exception could be a good solution here. There are some times when a potentially empty shared_ptr might also be returned. This would need to be checked in the same way as a weak_ptr.
In that case, I would assume only in a threaded environment, would such a check not be viable for a weak_ptr (but fine for a shared_ptr due to holding the ref count).
3
u/pdimov2 Nov 22 '21
Also known as
shared_ptr<T> weak_ptr<T>::operator->() const { return shared_ptr<T>( *this ); }
14
u/mt-wizard Nov 21 '21
there are couple:
lock() may fail, and the
emp2->...example would become a null-pointer dereference, so, a UB, with no good way to avoid. It's basically giving you a loaded gun already aimed at the footeven not thinking about #1, it promotes an inefficient way of locking once per each operation, invoking extra atomic refcount operations where totally unnecessary. Without such operator you have to explicitly write
.lock()-> more thought given, resulting in better codeResetting a locked pointer and then using it is quite a special case to protect against. I'd say that as with whole C++, once you're dealing with lifetimes, you simply have to understand what's going on. Not resetting a local variable is among the simplest things to keep track
0
u/pedersenk Nov 21 '21 edited Nov 21 '21
Thanks for the suggestions. Going through them, would the following not be suitable arguments against?
Throwing an exception rather than NULL dereference. The STL does tend to minimize their use (and checking shared_ptr for NULL dereference would be wasteful for every access). However there is some evidence of use; i.e in vector::at() vs vector::operator[](size_t).
Surely typing
lock()could potentially just become muscle memory, negating that kind of guidance? OK, my argument is a little bit weak here.I do occasionally see this kind of mistake in the wild. Sometimes iterating through a vector whilst further down, pushing something back (invalidating the contents). I saw it most recently in some GUI code removing a parent UiPanel during a child UiButton's callback. Sure, I do understand we can't easily handle every case for this; the programmer does have to think a little.
7
u/mt-wizard Nov 21 '21
As someone else already pointed,
weak_ptr's primary purpose is to be used when the target may not always exist. For those cases having an exception thrown doesn't align with the concept of exceptions - to indicate exceptional situations.Unfortunately, one also needs
weak_ptrin a different case - to break dependency cycles, like using it abackpointer in a graph orparentin a tree. For these cases you can actually guarantee that the pointer is never weak - and then thisoperator ->makes total sense.I'd say that the pitfalls it brings to the original use are bad enough that it's fine to make the cycle breaking usage a bit less clean. This was probably the reason behind the API design.
4
u/beedlund Nov 22 '21
Usually prefer
if ( auto shared = weak.lock() )
{
shared->use_shared();
}It's compact and clear though I'm not 100% how visibility shared is outside the if block.
1
u/pedersenk Nov 22 '21
Yes, this is similar to how I would expect the standard weak_ptr to be used.
sharedis also only visible within the if block. This is obviously fine (and from the comments here seems to be the way to go).My suggestion was particularly for this use case where you only call one function (
use_shared()) on the locked weak_ptr. Mainly so you can avoid some additional lines of code and achieve exactly the same thing. However the expense seems to be at the explicit checking of the result oflock(and without throwing exceptions etc).
10
u/pdimov2 Nov 21 '21
First, lock() can fail. So when you do
emp2->calculateWage();and lock() returns an empty shared_ptr, this will crash.
Second, if you do more than one thing, e.g.
emp2->do_this();
emp2->do_that();this causes lock() to be called twice, and this inefficiency is not visible in the source code, and is even encouraged by the more convenient syntax.
That's why you're forced to spell the lock() explicitly, and check for failure.
if( auto sp = emp2.lock() )
{
sp->do_this();
sp->do_that();
}
else
{
// handle failure
}5
u/jeanlemotan Nov 21 '21
One reason is that it would not allow you to check for nullptr, and it would be too simple for this to became how ppl use weak_ptr by default.
5
u/Troldemorv Nov 22 '21
If you do not test for null after lock(), it means you want a valid pointer at all time, so a shared_ptr, not a weak_ptr. To me, if you reach this point, it means you don't have a good idea of the life cycle of your objects or you put to much on the shared_ptr mechanism.
To break the ptr loop, you can introduce a weak_ptr but first, you should ask if you really need a shared_ptr between the child and the parent.
Can the child outlive the parent ? If no, you can probably use a simple pointer to keep the parent at the child level. Doing so, if you still need to give the parent shared_ptr to others from the child, you can just create one on the fly, the counter is still the same and shared with other instance of shared_ptr on the same object
If the life cycle is driven by the child - the parent exists as long as there is at least a child pointing at it - then, maybe it's the parent-child link that should be a weak_ptr.
4
u/KingAggressive1498 Nov 21 '21
If the weak pointer isn't wrapping valid data, it would have to return nullptr, which you'd think would be a segmentation fault but actually might not be.
When would it not be a segmentation fault? The operator might be calling a non-virtual member function that doesn't have to access any data members.
This could actually be a serious program error if that function changes global state, or if the return value of a "pure" such function gets used, when it shouldn't be because the validity of the weak_ptr was supposed to represent the validity of doing such things.
So we just need test against nullptr and maybe throw an exception! But there's problems with this:
There's nothing exceptional about a weak_ptr referencing nothing, that's literally why they exist.
you're turning a perfectly noexcept interface into an exception throwing one. Because exception handling isn't free, now we have an interface with overhead that isn't necessary.
if I don't want to (or can't) handle exceptions, this is now a termination point in my program the reason for which is not predictable, might not be easily reproducible, and depends entirely on the ever-changing state of some small part in my program. That makes it a bug that's hard to chase down.
It's also just bad semantics. The .lock() method clearly tells anyone reading the code something that -> only implies to someone who understands the implementation.
1
u/NilacTheGrim Nov 22 '21
Because it's unsafe. Especially in a multithreaded environment, where it's insufficient to just check if valid -- you must lock to guarantee the object is still alive throughout the life of the call that uses it.
2
u/pedersenk Nov 22 '21
You will see in my example implementation of
weak_ptr::operator->that I do lock during access. This implicitly works by returning a shared_ptr which is then accessed via -> drilldown.The issue is that there is no explicit check; instead I would have to rely on exceptions if the weak_ptr was invalid. For my use-case (even multi-threaded), that is reasonable because for that weak_ptr to be NULL in my case really is an exception circumstance. However I understand that is not the case for many other peoples use-cases.
2
u/NilacTheGrim Nov 22 '21
Ah, I didn't realize you actually do lock it with a shared. Well, if in your app that's truly exceptional, then you should definitely use it that way as a sort of syntax sugar. There's more than 1 way to skin the cat. I personally like this idiom:
if (auto shared = weak.lock()) { shared->doStuff(); // ... }It's nice and neat to me. But -- if you think in your app it's just syntax noise, and that the ptr really should be alive then, more power to you.
I would say though that if you can guarantee that anyway in your app, as others have pointed out, then maybe you don't need a shared_ptr / weak_ptr combination at all, in the first place... Unless the guarantee isn't very strong and it does sometimes go away like 1% of the time... in that case I guess an exception may work especially if you plan on accessing it a lot deep into the stack and you like the idea of jumping back out 7 layers deep to handle the exception and abort the operation. That can work...
1
u/pedersenk Nov 22 '21
I would say though that if you can guarantee that anyway in your app, as
others have pointed out, then maybe you don't need a shared_ptr /
weak_ptr combination at allAgreed, though possibly this is where I tend to be misusing C++ in that I don't like the idea of having any potentially unsafe code (not that "unsafe" code is actually unsafe but has the potential to be if the programmer (i.e me on a bad day) screws up. I.e whilst I can guarantee the weak_ptr should be valid in my program design; I often make mistakes! I actually use weak_ptr mainly as a tool to find this (sanitizers are 95% accurate these days but I find weak_ptr and other observers 100% accurate).
I think I am fairly alone in this however so that is OK. But I suppose it did give me a slightly flawed outlook on how others were using weak_ptr and that an
operator->was not enough.
3
u/Myrgy Nov 21 '21
I think the reason to do not overload-> is because weak_ptr is not a pointer itself. For any pointer we can compare with nullptr and then use -> operator (raw, unique, shared, optional)
In case of weak_ptr such comparison doesn't make any sense. Thats why its better to do not provide odd api and force better and robust usage:
if (std::shared_ptr<T> p = weak.lock()) { p->foo(); }
3
u/Som1Lse Nov 22 '21
There is a very good reason not to have operator-> for std::weak_ptr, which I'll get to, but I want to address some other points first:
As people have said, you will not generally know that a std::weak_ptr is never null. When you do, it is usually a sign of poor design: If you know the object will always be alive, a raw pointer suffices, since you don't need to keep track of its lifetime.
That said, sometimes incidental situations happen where you know a std::weak_ptr will never be null. I'd say it is still a code smell, but real code has smells, and not all of them are worth cleaning up.
Let's assume we are definitely in the case where it is perfectly valid to just blindly dereference the pointer:
Why is
ptr->calculateWage()so preferred overptr.lock()->calculateWage()? The latter is only 7 more characters, and makes it clear what we are doing.It invites bad habits: Even if we are 100% right to dereference the
std::weak_ptr, we might be dereferencing it more than once. Say someone comes along later and decides the formula should beptr->calculateWage()*ptr->contractLengthInMonths()+ptr->bonuses(). Even if a blind dereference was fine, it is less efficient thanlock()ing it, and then dereferencing thestd::shared_ptr.It is not searchable: I can
grepfor.lock()->. I cannotgrepfor all "operator->onstd::weak_ptrs only".It is still wrong most of the time: If you need a
std::weak_ptrthen by definition you don't always know whether it is null. Adding aoperator->, while perfectly valid in some cases, is not a good idea for the majority of cases, and makes it easier to write bugs.
That last point is the real reason, I think, why it doesn't exist: We don't optimise an API for the rare case; we optimise for the common case. It is the same reason downcasting requires an explicit static_cast (or a C-cast) and why narrowing conversions should require one, and for what it is worth .lock() is a lot shorter than static_cast.
51
u/witcher_rat Nov 21 '21
And what if
lock()returns an emptyshared_ptrbecause the shared object was already destroyed?That is after all one of the main points of a
weak_ptr.So if they allowed
weak_ptr<T>::operator->()to return ashared_ptrand it was empty, and you had invokedemp2->calculateWage()... boom goes the dynamite.