このようなクラスを作成する場合:
class Test {
public:
...
private:
string s1_;
string s2_;
vector<int> v_;
};
2 つの文字列とベクトルを受け入れるコンストラクターを宣言する最良の方法は何ですか? より具体的には、左辺値と右辺値の参照をどのように処理しますか?
次の 3 つのオプションが表示されます。
lvref と rvref のすべての組み合わせを作成します。
Test(const string& s1, const string& s2, const vector<int>& v) : s1_{s1}, s2_{s2}, v_{v} { ... } Test(const string& s1, const string& s2, vector<int>&& v) : s1_{s1}, s2_{s2}, v_{move(v)} { ... } Test(const string& s1, string&& s2, const vector<int>& v) : s1_{s1}, s2_{move(s2)}, v_{v} { ... } Test(const string& s1, string&& s2, vector<int>&& v) : s1_{s1}, s2_{move(s2)}, v_{move(v)} { ... } Test(string&& s1, const string& s2, const vector<int>& v) : s1_{move(s1)}, s2_{s2}, v_{v} { ... } Test(string&& s1, const string& s2, vector<int>&& v) : s1_{move(s1)}, s2_{s2}, v_{move(v)} { ... } Test(string&& s1, string&& s2, const vector<int>& v) : s1_{move(s1)}, s2_{move(s2)}, v_{v} { ... } Test(string&& s1, string&& s2, vector<int>&& v) : s1_{move(s1)}, s2_{move(s2)}, v_{move(v)} { ... }
長所: あらゆる可能性が効率的に処理されます。
短所: すべての組み合わせを処理するには大量のコードが必要であり、エラーが発生しやすい可能性があります。
常に引数をコピーして移動します。
Test(string s1, string s2, vector<int> v) : s1_{move(s1)}, s2_{move(s2)}, v_{move(v)} { ... }
長所: 担当者は 1 人だけです。
短所: 移動は自由を意味しないため、効率的ではありません。
「ユニバーサル リファレンス」を使用します。
template <typename S1, typename S2, typename V> Test(S1&& s1, S2&& s2, V&& v) : s1_{forward<S1>(s1)}, s2_{forward<S2>(s2)}, v_{forward<V>(v)} { ... }
長所: 1 人の担当者がすべてを効率的に処理します。
短所:あまり意味がない。s1、s2、v とは? さらにエラーが発生しやすくなる可能性があります (
Test error{1,2,3}
コンパイルなど)。
それを達成するためのより良い方法はありますか?