emplace_back()的行为不如预期 [英] emplace_back() does not behave as expected

查看:134
本文介绍了emplace_back()的行为不如预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的程序来在标准库容器中就地创建对象。这是我写的:

  #include< vector& 
#include< iostream>

class AB
{
public:
explicit AB(int n);
AB(const AB& other)= delete;
AB(AB&&&其他);
AB& operator =(const AB& other)= delete;
AB& operator =(AB&&& other)= default;
private:
int i;
};

AB :: AB(int n):i(n)
{
std :: cout< 对象已创建。 << std :: endl;
};

AB :: AB(AB&& other):i(std :: move(other.i))
{
std :: cout< 对象移动了。 << std :: endl;
};

int main()
{
std :: vector< AB> v;
v.emplace_back(1);
v.emplace_back(2);
v.emplace_back(3);
};

我用g ++(4.8.2版本)编译。运行输出后,我得到:

 创建对象。 
创建对象。
对象移动。
创建对象。
对象已移动。
对象已移动。

但我期待这样:

 创建对象。 
创建对象。
创建对象。

我认为放置的整个点是摆脱运动构造函数调用。

解决方案

问题是,当你添加更多的元素,导致额外的移动,你的矢量正在调整大小。如果您在开始时预留足够的容量,则会得到预期的结果:

  std :: vector< AB> v; 
v.reserve(3);
v.emplace_back(1);
v.emplace_back(2);
v.emplace_back(3);

提供

 创建对象。 
创建对象。
创建对象。

在gcc 4.8.2上。请注意,您可以通过查看 v.capacity()来跟踪向量在原始代码中的增长。


I wrote a simple program to play around with in-place creation of objects inside standard library containers. This is what I wrote:

#include <vector>
#include <iostream>

class AB
{
public:
   explicit AB(int n);
   AB(const AB& other) = delete;
   AB(AB&& other);
   AB& operator=(const AB& other) = delete;
   AB& operator=(AB&& other) = default;
private:
   int i;
};

AB::AB(int n): i( n )
{
   std::cout << "Object created." << std::endl;
};

AB::AB(AB&& other): i( std::move(other.i) )
{
   std::cout << "Object moved." << std::endl;
};

int main()
{
   std::vector< AB > v;
   v.emplace_back(1);
   v.emplace_back(2);
   v.emplace_back(3);
};

I compiled it with g++ (version 4.8.2). After running the output, I got:

Object created.
Object created.
Object moved.
Object created.
Object moved.
Object moved.

But I expected something like this:

Object created.
Object created.
Object created.

I thought the whole point of emplacement was to get rid of the movement constructor calls. Are there any requirements in class AB that are not met?

Thanks for your help.

解决方案

The problem is that your vector is being resized as you add more elements, resulting in extra moves. If you reserve enough capacity at the start, you get the expected result:

   std::vector< AB > v;
   v.reserve(3);
   v.emplace_back(1);
   v.emplace_back(2);
   v.emplace_back(3);

gives

Object created.
Object created.
Object created.

On gcc 4.8.2. Note that you can track the vector's growth in your original code by looking at v.capacity().

这篇关于emplace_back()的行为不如预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆