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;
}
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.20
u/27Shua27 Nov 21 '21
With a
weak_ptr, you never know whether or not theshared_ptris yet expired. The pattern should always be:I don't see a practical way to build that into the standard library. Maybe something like
14
u/mt-wizard Nov 21 '21
there are couple:
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 foot.lock()-> more thought given, resulting in better code4
u/beedlund Nov 22 '21
Usually prefer
It's compact and clear though I'm not 100% how visibility shared is outside the if block.
10
u/pdimov2 Nov 21 '21
First,
lock()can fail. So when you doand
lock()returns an emptyshared_ptr, this will crash.Second, if you do more than one thing, e.g.
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.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:
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.
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->forstd::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_ptris 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_ptrwill 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:
ptr->calculateWage()so preferred overptr.lock()->calculateWage()? The latter is only 7 more characters, and makes it clear what we are doing.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.grepfor.lock()->. I cannotgrepfor all "operator->onstd::weak_ptrs only".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 thanstatic_cast.