在下面的代码中,我得到两个构造函数调用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
}
Run Code Online (Sandbox Code Playgroud)
小智 7
用户声明的析构函数,即使它是默认的,也意味着不会生成移动构造函数.
12.8复制和移动类对象[class.copy]
9如果类的定义
X没有显式声明一个移动构造函数,那么当且仅当一个类的定义被隐式声明为默认值时[...]
(9.4) -
X没有用户声明的析构函数.
如果生成了移动构造函数,那么它比模板构造函数更适合移动.它不保存构造函数调用,它只是意味着调用不同的构造函数,一个不打印任何东西的构造函数.
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |