在下面的代码中,我得到了的两个构造函数调用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
}
用户声明的析构函数,即使它是默认的,也意味着不会生成任何move构造函数。
12.8复制和移动类对象[class.copy]
9如果一个类的定义
X
没有显式声明一个move构造函数,则当且仅当[...]
(9.4)-
X
没有用户声明的析构函数。
如果生成了move构造函数,那么它比模板构造函数更适合移动。它不会保存构造函数调用,只是意味着将调用另一种构造函数,而该构造函数不会打印任何内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句