C ++ Unable to move unique_ptr with generic links

Consider this code:

template<typename T>
T mov(T&& t){
   return std::move(t);
}

int main(){
   std::unique_ptr<int> a = std::unique_ptr<int>(new int());
   std::unique_ptr<int> b = mov(a);
}

The function movshould simply take a universal reference and return it by value, but moveuse it instead move. Thus, when calling this method, you do not need to copy. Therefore, it should be good to name such a function with the help of unique_ptrwhich you can only move. However, this code does not compile: I get an error message:

test.cpp:24:34: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’
    std::unique_ptr<int> b = mov(a);

So it looks like C ++ is trying to call the unique_ptrcopy constructor , which of course has been removed. But why is a copy going on here? How can I get this code to compile?

+4
2

, mov

#include <utility>
#include <memory>
template<typename T>
typename std::remove_reference<T>::type&& mov(T&& t){
   return std::move(t);
}

int main(){
   std::unique_ptr<int> a = std::unique_ptr<int>(new int());
   auto b = mov(a);
}

, , . , ;

template<typename T>
typename std::remove_reference<T>::type mov(T&& t){
   return std::move(t);
}
+3

- . , , . rvalue; . :

template<typename T>
T&& mov(T&& t){
   return std::move(t);
}

, T&& , rvalue. , lvalue T& mov(T& t). - , std::move lvalue. , , :

test.cpp:18:22: error: invalid initialization of non-const reference of type 

std::unique_ptr<int>&’ from an rvalue of type ‘std::remove_reference<std::unique_ptr<int>&>::type {aka std::unique_ptr<int>}’
    return std::move(t);

, rvalue . , , , , , std::remove_reference T, &&, rvalue T&&, , mov :

template<typename T>
typename std::remove_reference<T>::type&& mov(T&& t){
   return std::move(t);
}

, remove_reference &&:

template<typename T>
typename std::remove_reference<T>::type mov(T&& t){
   return std::move(t);
}
+3

All Articles