c++ - Add implicit conversion from unique_ptr<T> to T* -
general question: without going whether or not it's idea, how can add implicit conversion operator class has been defined? example, let's i want unique_ptr<t> implicitly convert t*, can't add member conversion operator because can't change definition of unique_ptr class.
options:
is there c++ voodoo can use make happen without creating member function?
answer-so-far: no.
there no way add implicit conversion away type can't modify in code.
just ... sadness.could derive std::unique_ptr , add own member conversion function? there serious downsides this?
answer-so-far: yes (from vsoftco)
downsides yet determined. far inheriting std::unique_ptr, inheriting constructors, , declaring implicit conversion operator has worked splendidly hardly code needing written.am going have live without rest of life?
answer-so-far: we'll see...
if can option 2 , running without serious side-effect or burdens, i'll test out while , report on whether think it's worth it. we'll see!
example code:
#include <algorithm> #include <memory> #include <vector> struct myclass { myclass(int v) : value(v) {} int value; }; int main() { auto vec = std::vector<std::unique_ptr<myclass>>(); vec.push_back(std::make_unique<myclass>(1)); vec.push_back(std::make_unique<myclass>(2)); // error c2664: 'void (__vectorcall *)(myclass *)' : cannot convert argument 1 'std::unique_ptr<myclass,std::default_delete<_ty>>' 'myclass *' std::for_each(std::begin(vec), std::end(vec), [](myclass* myclass) { myclass->value += 3; }); }
if don't want use std::unique_ptr<>::get()
function, can:
define free function takes
std::unique_ptr
, returns raw pointer returnedget
, although don't think makes code better, like:// free function template<typename t> t* get_raw_ptr(const std::unique_ptr<t>& up) { return up.get(); }
conversions of
unique_ptr
raw pointers ok, have explicit. implicit conversion may lead lots of headaches, since may happen when least expect them.it bad idea derived
std::unique_ptr
, latter not made used base class (doesn't have virtual destructor). in general, bad derive standard library classes. however, if insist, can use wrapper in define implicit conversion operator, like:// wrapper template <class t, class deleter = std::default_delete<t>> class unique_ptr_wrapper: public std::unique_ptr<t, deleter> { public: using std::unique_ptr<t, deleter>::unique_ptr; // inheriting base ctors operator t* () const {return this->get();} };
and use
// wrapper usage: unique_ptr_wrapper<int> upw{new int{42}}; int* p = upw; // implicit conversion ok
- 1 , 2 can you, may improve life ;)
Comments
Post a Comment