在下面的代碼中,我得到了兩個構造函數調用Test u = "u";
。但是,如果我註釋掉析構函數,那麼我只能獲得一個構造函數調用。這是爲什麼?爲什麼構造函數調用依賴於缺省析構函數的存在?
#include <iostream>
template<class T>
auto operator<<(std::ostream& os, const T& t) -> decltype(t.print(os), os)
{
t.print(os);
return os;
}
class Test
{
public:
template<typename T>
Test(T&& t)
{
std::cout << "Test " << t << '\n';
}
~Test() = default; // if commented out removes one construction
void print(std::ostream& os) const
{
os << "[with T = Test]";
}
};
int main()
{
Test u = "u"; // two constructors (second, a temporary, with T = Test)
Test t("t"); // one constructor
}
問題是什麼?你問爲什麼'u'有兩個構造函數調用,而't'有一個? – NathanOliver
是的。爲什麼當默認的析構函數被註釋掉時,它會成爲一個? – QuentinUK
請更清楚地提出問題,我看不到你在問什麼。 – SergeyA