5 ms·
There’s a number of fun C++ ones similar in spirit: std::move, for example.
by saagarjha 7y ago
There’s a number of fun C++ ones similar in spirit: std::move, for example.
- codeflo 7y agostd::move's implementation not quite as elegant, though (this is from the GCC source): template<typename _Tp> constexpr typename std::remove_reference<_Tp>::type&& move(_Tp&& __t) noexcept { return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }
- saagarjha 7y agoIt’s a bit ugly because the standard library functions are replete with underscores, and of course it isn’t empty. But I still think it’s quite surprising, as most people would think it actually does some sort of semantic “move”.
- saghm 7y ago> It’s a bit ugly because the standard library functions are replete with underscores, and of course it isn’t empty. I'll be honest, neither of those are my top issue with that in terms of why I think it's ugly.
- jcelerier 7y agoThe standard C++ way to free resources is the character '}'
- deleted 7y ago[deleted]
- wwright 7y agoRust has the exact same semantics there. Drop is useful when you need to explicitly notate that a value should end its life early.
- klipt 7y agovoid drop(unique_ptr<T>&& x) {} Would do the same in C++ for values held by unique_ptr: take ownership of the pointer and then free it.
- SamReidHughes 7y agoNo, it would not free it. It takes a reference to the pointer and does nothing.
- dkersten 7y agounique_ptr disposes of the object its holding when it goes out of scope unless passed to another unique_ptr or ownership is explicitly released. Presumably klipt would std::move the unique_ptr, hence the universal reference (which seems unnecessary, just pass it by value). Am I missing something? Does it not work with std::move?
- Rusky 7y agoYes, you're missing that the type `T&&` is a reference, not a value, and so does not run the object's destructor when it goes out of scope.
- dkersten 7y agoSorry, I edited right after hitting reply to clarify that I'm assuming the intention was to std::move the unique_ptr in, since it was T&& and not T&. Would that still not work?
- Rusky 7y agoIt would still not work. All std::move does is cast to T&&, enabling overload resolution to pick a function with T&& as its parameter type.
- perspective1 7y agoTell that to the enormous heap object you just forgot you made earlier.