学习C++,关于构造函数的问题很少。

请考虑以下代码:

#include<stdio.h>
#include<iostream>

// Case 1

class CFoo
{
public:
    CFoo()  { printf("CFoo constructor: user-defined default\n"); }
    ~CFoo() { printf("CFoo destructor\n"); }
};

void testFoo()
{
    CFoo foo0;              // A way to use default constructor
    CFoo foo1 = CFoo();     // Another way to use default constructor
    CFoo foo2 = CFoo(foo1); // Using implicit copy constructor

    // Output:
    //     CFoo constructor: user-defined default
    //     CFoo constructor: user-defined default
    //     CFoo destructor
    //     CFoo destructor
    //     CFoo destructor
    //     CFoo destructor
}

// Case 2

class CBar
{
public:
    CBar() { printf("CBar constructor: user-defined default\n"); }
    CBar(CBar & other) = delete;
    ~CBar() { printf("CBar destructor\n"); }
};

void testBar()
{
    CBar bar0;
    // line 44: error C2280: 'CBar::CBar(CBar &)': attempting to reference a deleted function
    // line 34: note: see declaration of 'CBar::CBar'
    // line 34: note: 'CBar::CBar(CBar &)' : function was explicitly deleted
    // CBar bar1 = CBar(); // Why this has anything to do with the copy constructor?

    // Output:
    //     CBar constructor: user-defined default
    //     CBar destructor
}

// Case 3

class CBaz
{
public:
    CBaz()             { printf("CBaz constructor: user-defined default\n"); }
    CBaz(CBaz & other) { printf("CBaz constructor: user-defined copy\n"); }
    ~CBaz()            { printf("CBaz destructor\n"); }
};

void testBaz()
{
    CBaz baz0;
    CBaz baz1 = CBaz();
    CBaz baz2 = CBaz(baz1);

    // Output:
    //     CBaz constructor: user-defined default
    //     CBaz constructor: user-defined default
    //     CBaz constructor: user-defined copy
    //     CBaz destructor
    //     CBaz destructor
    //     CBaz destructor
}

// main

void main() {
    testFoo();
    testBar();
    testBaz();

    std::cin.get();
}

问题:
  • 为什么不能像使用CBar一样将CBar bar1 = CBar();的实例创建为CFoo
  • testFoo调用4个析构函数。其中3个用于foo0,foo1和foo2。 4号从哪里来? testBaz具有相同的结构,但仅调用3个析构函数。 CFooCBaz之间的唯一区别是CBaz具有用户定义的副本构造函数。
  • 最佳答案


    CBar的副本构造函数被删除。因此,CBar是不可复制的。因此,您无法复制初始化CBar
    CFoo是可复制的,因此没有问题。


    T object = other;是副本初始化的语法。



    除了命名对象(变量)之外,还构造了两个临时对象CFoo()CFoo(foo1)。无论出于何种原因,这些临时成员中只有一个被复制删除优化了。



    这在某种程度上影响了优化器。我认为没有理由不能同时优化两个CFoo的临时工,但是没有一个。对于它的值(value),我的编译器确实对两者进行了优化。

    PS。 CBaz baz1 = CBaz();格式错误,因为非常量左值引用无法绑定(bind)到临时对象。

    PPS。 void main()格式错误,因为main必须返回int

    关于c++ - 为什么删除拷贝构造函数会影响用户定义的默认构造函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46244513/

    10-11 22:32
    查看更多