2

为什么在下面的代码中会出现一对“额外的”复制构造函数和破坏?

当叮咚的构造函数将 STL 容器作为参数时会发生这种情况(我尝试过 std::vector 和 std::list)。它可能发生在其他事情上吗?如果构造函数取而代之的是指针,则不会发生。如果我在堆上分配 ding 也不会发生( Dingledong* ding = new Dingledong(v) )。

#include <list>
#include <iostream>

class Dingledong{
public:
    Dingledong(std::list<int> numbers)
    {
        std::cout << "construction\n";
        numbers_ = numbers;
    }
    Dingledong(Dingledong const& other)
    {
        std::cout << "COPY construction\n";
    }
    ~Dingledong()
    {
        std::cout << "destructed\n";
        // I would do some cleanup here.. unsubscribe from events, whatever..
        // but the destructor is called sooner than I would expect and thus
        // the cleanup is done prematurely.
    }
    std::list<int> numbers_;
};

void diller()
{
    std::cout << "diller started.. " << std::endl;
    std::list<int> v = std::list<int>(34);
    // Having an STL container as parameter in constructor causes Dingledong's copy constructor to 
    // be used to create a temporary Dingledong which is immediately destructed again. Why?
    Dingledong ding = Dingledong(v);
    std::cout << "Has ding been destructed?\n";
}

int main()
{
    diller();
    system("pause");
}

输出:

diller started...
construction
COPY construction     // I didn't expect this to happen
destructed            // I didn't expect this to happen
Has ding been destructed?
destructed

先感谢您!

4

2 回答 2

4

这段代码:

Dingledong ding = Dingledong(v);

方法:

  1. 创建类型的临时对象Dingledong,初始化为v
  2. 创建对象ding,用临时对象初始化。

复制构造函数出现在此处的第 2 步。如果您不想要副本,请不要编写指定副本的代码。例如:

Dingledong ding(v);   // no copy

编译器可以实现一个称为复制省略的功能,其中优化了这个临时对象(即使复制构造函数有副作用),但他们不必这样做,在这种情况下没有理由依赖它。


您可以通过添加移动构造函数来改进代码,在这种情况下(如果编译器不执行复制省略)操作将是移动而不是复制,这样成本较低。

您的构造函数中还有一个浪费的副本(numbers从 复制v,然后numbers_从 复制numbers,并且还被numbers_初始化然后分配,而不是仅仅被初始化)。这将是一个更好的构造函数:

Dingledong(std::list<int> numbers): numbers_( std::move(numbers) )
{
    std::cout << "construction\n";
}
于 2015-11-10T22:53:38.560 回答
1

你的输出:

diller started...
construction                //(1)
COPY construction           //(2)
destructed                  //(3)
Has ding been destructed?
destructed                  //(4)

以及相关的代码:

Dingledong ding = Dingledong(v);

Dingledong(v) 创建一个临时对象。(1) 印刷。

您将此临时对象分配给 ding(实际上,这是调用复制构造函数的语法糖)。(2) 印刷。

一旦语句完成,临时对象就会被销毁。(3) 印刷。您的代码运行,一旦 ding 超出范围,它就会被销毁, (4) 会被打印出来。

于 2015-11-10T23:02:00.897 回答