![](/img/trans.png)
[英]Why does std::is_nothrow_move_assignable depend on the presence of a destructor?
[英]Why does the constructor call depend on the default destructor's presence?
在下面的代码中,我得到了两个Test u = "u";
构造函数调用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
的定义未明确声明移动构造函数,则仅当且仅当将隐式声明为默认构造函数[...]
(9.4)
X
没有用户声明的析构函数。
如果生成了移动构造函数,那么比模板构造函数更适合移动。 它不会保存构造函数调用,只是意味着将调用另一种构造函数,而该构造函数不会打印任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.