I stumbled upon a code similar to this while debugging a crash due to de-referencing a dangling piece of memory.
template<typename RaiiObject, typename HandleType>
const HandleType& ExtractHandle(const RaiiObject &value){
const HandleType* val = value.get(); // get underlying managed object
return static_cast<const HandleType&>(*val);
}
On the caller side the code looked like this:
const auto &x = ExtractHandle(GetAHandle());
This is a definitely a problem because the reference to the underlying object that we will be getting from ExtractHandle
will be dangling since the Raii object managing it would have expired.
Now the dev fixing this issue replaced the capture by reference to capture by value.
auto x = ExtractHandle(GetAHandle());
His claim is that since we are making a copy, we are safe since the x-value returned by GetAHandle will not die till the copy constructor for Handle is invoked. Is this assumption correct? Is it well defined by standard that the above proposed fix is not UB?
Note: While the correctness and utility of this design can definitely be questioned, the point is more around whether copying by value guarantees a well defined behavior
Aucun commentaire:
Enregistrer un commentaire