为什么构造函数调用依赖于默认析构函数的存在?

时间:2016-02-16 14:32:02

标签: c++

在下面的代码中,我得到了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
}

1 个答案:

答案 0 :(得分:7)

用户声明的析构函数,即使它是默认的,也意味着不会生成移动构造函数。

  

12.8复制和移动类对象[class.copy]

     

9如果类X的定义未明确声明移动构造函数,则当且仅当

时,将隐式声明一个默认值。      

[...]

     

(9.4) - X没有用户声明的析构函数。

如果生成了移动构造函数,那么它比模板构造函数更适合移动。它不保存构造函数调用,它只是意味着调用不同的构造函数,不会打印任何构造函数。