简体   繁体   English

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

[英]Why does the constructor call depend on the default destructor's presence?

In the following code, I get two constructor calls for Test u = "u"; 在下面的代码中,我得到了两个Test u = "u";构造函数调用Test u = "u"; . However, if I comment out the destructor, then I only get one constructor call. 但是,如果我注释掉析构函数,那么我只会得到一个构造函数调用。 Why is that? 这是为什么?

#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
}

The user-declared destructor, even if it is defaulted, means no move constructor gets generated. 用户声明的析构函数,即使默认设置也意味着不会生成任何move构造函数。

12.8 Copying and moving class objects [class.copy] 12.8复制和移动类对象[class.copy]

9 If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if 9如果类X的定义未明确声明移动构造函数,则仅当且仅当将隐式声明为默认构造函数

[...] [...]

(9.4) -- X does not have a user-declared destructor. (9.4) X没有用户声明的析构函数。

If a move constructor is generated, then it is a better candidate for moves than your template constructor. 如果生成了移动构造函数,那么比模板构造函数更适合移动。 It doesn't save a constructor call, it just means a different constructor gets called, one that doesn't print anything. 它不会保存构造函数调用,只是意味着将调用另一种构造函数,而该构造函数不会打印任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么std :: is_nothrow_move_assignable取决于析构函数的存在? - Why does std::is_nothrow_move_assignable depend on the presence of a destructor? 为什么这会调用默认构造函数? - Why does this call the default constructor? 为什么显式默认析构函数会禁用默认移动构造函数? - Why does an explicitly defaulted destructor disable default move constructor? 为什么空向量调用值类型的默认构造函数? - Why does an empty vector call the value type's default constructor? C ++:默认的复制构造函数是否受到其他构造函数和析构函数的影响? - C++: Is default copy constructor affected by presence of other constructors and destructor? 为什么结构体的析构函数是否运行取决于成员变量的类型? - Why does whether a struct's destructor runs depend on the type of a member variable? 从默认构造函数调用的成员的析构函数 - Member's destructor calling from default constructor 为什么类的默认构造函数和析构函数是内联的? - Why are the default constructor and destructor of a class inline? 为什么复制构造函数调用其他类的默认构造函数? - Why does copy constructor call other class' default constructor? 为什么调用重载的构造函数会导致调用默认构造函数? - Why does calling an overloaded constructor cause a call of the default constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM