emplace_back() does not behave as expected(emplace_back() 未按预期运行)
问题描述
我编写了一个简单的程序来尝试在标准库容器中就地创建对象.这是我写的:
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);
};
我用 g++(4.8.2 版)编译它.运行输出后,我得到:
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.
但我期待的是这样的:
Object created.
Object created.
Object created.
我认为安置的全部意义在于摆脱移动构造函数调用.AB类有什么要求没有满足吗?
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?
感谢您的帮助.
推荐答案
问题是当您添加更多元素时,您的矢量正在调整大小,从而导致额外的移动.如果一开始就预留了足够的容量,就会得到预期的结果:
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);
给予
Object created.
Object created.
Object created.
在 gcc 4.8.2 上.请注意,您可以通过查看 v.capacity() 来跟踪原始代码中向量的增长.
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() 未按预期运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:emplace_back() 未按预期运行
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
