c++ - Copying std::unique_ptr's value via dereferencing -
c++ - Copying std::unique_ptr's value via dereferencing -
i wrote next code seek re-create value of unique_ptr
object structure.
#include <iostream> #include <memory> using namespace std; struct s { s(int x = 0, int y = 0):x(x), y(y){} // s(const s&) {} // s& operator=(const s&) { homecoming *this; } int x; int y; std::unique_ptr<s> ptr; }; int main() { s s; s.ptr = std::unique_ptr<s>(new s(1, 4)); s p = *s.ptr; // re-create pointer's value homecoming 0; }
it pops errors in visual c++ 2012:
intellisense: no suitable user-defined conversion "s" "s" exists intellisense: no operator "=" matches these operands operand types are: std::unique_ptr> = std::unique_ptr> error c2248: 'std::unique_ptr<_ty>::unique_ptr' : cannot access private fellow member declared in class 'std::unique_ptr<_ty>'
unless uncomment lines attempted define re-create constructor , =operator. gets rid of compiler errors not intellisense errors. compiles regardless of intellisense errors showing in error list.
so, why cannot utilize default functions , compile them? doing re-create of value right way? how should define re-create constructor if needs one?
the re-create constructor no implicitly generate because have user defined constructor, why why effort re-create s
fails.
but still, unique_ptr
not copyable, movable, can utilize move constructor s
:
s(s&& other) : x(other.x), y(other.y), ptr(std::move(other.ptr)) { }
and phone call :
s p = std::move(s); // move s p
live demo
c++ c++11 unique-ptr visual-c++-2012
Comments
Post a Comment