我想了解如何完美轉發的作品,但我不明白爲什麼拷貝構造函數被調用下面的代碼中不明白爲什麼完美轉發不工作
#include <utility>
#include <iostream>
using std::cout;
using std::endl;
class Something {
public:
Something() = default;
Something(__attribute__((unused)) const Something& other) {
cout << "Copy constructor called" << endl;
}
Something(__attribute__((unused)) Something&& other) {
cout << "Move constructor called" << endl;
}
void print() {
cout << "Something::print() called" << endl;
}
};
void function_1(Something&& one) {
cout << "version two called" << endl;
Something inner{one};
inner.print();
}
void function_1(const Something& one) {
Something inner(one);
inner.print();
}
template <typename... T>
void test_function(T&&... ts) {
function_1(std::forward<T>(ts)...);
}
int main() {
const Something some1 {Something()};
test_function(some1);
test_function(Something());
return 0;
}
這將產生以下輸出
Copy constructor called
Something::print() called
version two called
Copy constructor called
Something::print() called
更改代碼以在右值引用中包含std::move
,但我並不期望需要它。當一個引用是一個右值引用時,正確的構造函數應該被自動調用嗎?正確的引用已解決,但正在調用錯誤的構造函數。任何幫助將不勝感激!
這應該很容易理解:只需在構造函數中設置一個斷點,當你打開它時,回溯會告訴你它是如何被調用的。這是調試器可以解決的最簡單的問題之一。 –
@SamVarshavchik我明白它是如何被調用的,但錯誤的超載被稱爲! – Curious
你怎麼說?你知道你需要明確地使用std :: move()來保存右值引用語義,對嗎? –