2016-05-09 1 views
-3

これらは同じ関数の定義ですが、最初にはmove(&&)を使用してパラメータが渡され、2番目のパラメータは(const &)を使用して渡されます。const&の代わりにmove(&&)が呼び出されるのはなぜですか?

template<typename T, class Allocator> 
void MyList<T, Allocator>::push_front(T && t) 
{ 
    Link<T>* newnode = new Link<T>(t); 

    if (empty()) { 
     head = std::move(newnode); 
     tail = std::move(newnode); 
     std::cout << "Linked List Created using move with value: " <<t<< std::endl; 
    } 
    else { 
     head->prev = std::move(newnode); 
     newnode->next = std::move(head); 
     head = std::move(newnode); 
     std::cout << "Node Inserted using move at the beginning of List with value: " <<t<< std::endl; 
    } 
} 

template<typename T, class Allocator> 
void MyList<T, Allocator>::push_front(const T & t) 
{ Link<T>* newnode = new Link<T>(t); 
    if (empty()) { 
     head = newnode; 
     tail = newnode; 
     std::cout << "Linked List Created with value: " <<t<< std::endl; 
    } 
    else { 
     head->prev = newnode; 
     newnode->next = head; 
     head = newnode; 
     std::cout << "Node Inserted at the beginning of List with value: " <<t<< std::endl; 
    } 
} 

私がメインで以下のコードを実行すると:

MyList<int> l1; 
    l1.push_front(5); 
    l1.push_front(std::move(8)); 

私はいつもmove機能のcoutを取得します。 const &はデフォルトのものでなければなりませんか?

+0

'std :: move(新しいリンク(t))'これはどうしようか?他の動き? – Slava

+0

@Slavaそうですね、私はどこにいても動かすことを追加していましたが、修正するつもりでしたが忘れました。ヘッドアップをありがとう!! – Bob

+4

プログラミングは推測では機能しないので、どこにでも盲目的に移動する代わりに何をしているのかを理解する必要があります – Slava

答えて

1

5はそれ自体が正の値です。これはコンパイラが&&呼び出しを安全に行うために、push_frontにのみ使用される一時的な値です。予想される動作を確認するには、左辺値を試してみてください。

MyList<int> l1; 
int foo = 5; 
l1.push_front(foo); 
l1.push_front(std::move(foo)); 

コンパイラはあなたが最初の呼び出しの後fooを使用して、したがって、const &を呼び出す必要がありますされていないことを確認することはできません。

+0

あなたの答えは正しくありません。最初の関数はlvalueで呼び出されます。 – Slava

+0

私は間違っていた、ごめんなさい – Slava

関連する問題