时会调用两次复制构造函数

时会调用两次复制构造函数

本文介绍了为什么在执行 vector.push_back 时会调用两次复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Class Child 和一个简单的向量推回实现,如下所示:

I have a Class Child, and a simple vector push back implementation like this:

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

class Child
{
    public:
        Child();
        Child(const Child &item);
        ~Child();
};

Child::Child()
{
    std::cout<<"Constructing Child\n";
}

Child::Child(const Child &item)
{
    std::cout<<"Copy-Constructing Child\n";
}

Child::~Child()
{
    std::cout<<"Destructing Child\n";
}

int main()
{
    std::vector<Child> v;
    Child Item1;
    v.push_back(Item1);
}

在调用 v.push_back( Item1 ); 之后,我有以下输出:

Right after v.push_back( Item1 ); is called, i have the following outputs:

Constructing Child
Copy-Constructing Child
Copy-Constructing Child
Destructing Child

我期待 Copy-Constructing Child 只出现一次.为什么复制构造函数会被调用两次?

I was expecting the Copy-Constructing Child only appears once. Why is the copy-constructor called twice?

推荐答案

发生这种情况是因为您使用的是旧编译器.对不起,如果这不是一个真正令人兴奋的结论.:-( 没有其他人可以复制这个问题,即使在较新的 Microsoft 编译器上也是如此.虽然 Richard Hodges 说编译器可以自由复制它认为合适的副本是正确的,但现代编译器会尽力避免它们.在特定的在您列出的情况下,一个体面的编译器不应该复制,如果您担心性能,您应该考虑升级到更新的版本.

This is happening because you are using an old compiler. Sorry if that isn't a really exciting conclusion. :-( No one else can replicate the problem, even on newer Microsoft compilers. While Richard Hodges is correct when he says that a compiler is free to make copies as it sees fit, modern compilers do their best to avoid them. In the specific case you list, a decent compiler should not be making a copy, and if you are concerned about performance you should consider upgrading to a newer version.

这篇关于为什么在执行 vector.push_back 时会调用两次复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:55