c++ - Who is responsible for deletion of heap allocated object when moving it? -
c++ - Who is responsible for deletion of heap allocated object when moving it? -
what happens when class created new, , move constructor of class executed? original creator still responsible deletion? illustration below runs fine (http://ideone.com/rs2lr9), shouldn't crash in sec scope since owner goes out of scope before vector , hence deletes object?
i misunderstanding here, happens ownership after std::move?
#include <iostream> #include <memory> #include <vector> #include <utility> class owner { public: owner() : data_(new int(1)) {} int& get() {return *data_;} private: std::unique_ptr<int> data_; owner(const owner&) = delete; void operator=(const owner&) = delete; }; int main() { { owner owner; std::vector<int> test; test.emplace_back(std::move(owner.get())); std::cout << test[0] << std::endl; } { std::vector<int> test; { owner owner; test.emplace_back(std::move(owner.get())); } std::cout << test[0] << std::endl; } { owner owner; { std::vector<int> test; test.emplace_back(std::move(owner.get())); std::cout << test[0] << std::endl; } } }
you're not moving info here. when phone call owner::get()
, you're exposing reference int
, , when phone call std::move()
on reference, you're making trivial cast. there's nil std::vector::emplace_back()
"steal" away owner
, because int
has no move constructor.
i'm guessing think std::unique_ptr
within owner
plays these operations, doesn't; you're dereferencing pointer, never attempting move content. so, you'd have invoke std::unique_ptr
's move constructor or assignment operator.
c++ c++11 move unique-ptr
Comments
Post a Comment