【发布时间】:2016-03-09 10:26:39
【问题描述】:
让我们考虑以下代码:
template<typename T>
void f(std::unique_ptr<T>&& uptr) { /*...*/ }
在另一个函数中:
void g()
{
std::unique_ptr<ANY_TYPE> u_ptr = std::make_unique<ANY_TYPE>();
f(std::move(u_ptr));
X: u_ptr->do_sth(); // it works, I don't understand why. Details below.
}
我不明白为什么u_ptr 中的X 还活着。
毕竟我强迫他被移动(std::move)。
---EDIT---
Ok, so now:
The code is still working:
class T{
public:
T(){}
void show(){
std::cout << "HEJ!\n";
}
};
void f(std::unique_ptr<T> ref){
ref->show();
}
int main()
{
std::unique_ptr<T> my;
my->show();
f(std::move(my));
my->show(); // How is it possible. Now, f takes unique_ptr by value
return 0;
}
【问题讨论】:
标签: c++ c++14 move-semantics unique-ptr