在emplace()中创建对象时复制省略号 [英] Copy elision when creating object inside emplace()

查看:55
本文介绍了在emplace()中创建对象时复制省略号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到许多工作中的代码,其中人们将emplace和emplace_back与一个临时对象一起使用,如下所示:

I see a lot of code at work where people use emplace and emplace_back with a temporary object, like this:

struct A {
    A::A(int, int);
};

vector<A> v;
vector<A>.emplace_back(A(1, 2));

我知道emplace_back的全部要点是能够直接传递参数,如下所示:

I know that the whole point of emplace_back is to be able to pass the parameters directly, like this:

v.emplace_back(1, 2);

但是不幸的是,这对一些人来说还不清楚.但是,我们不要再赘述了....

But unfortunately this is not clear to a few people. But let's not dwell on that....

我的问题是:编译器是否能够优化此设置并跳过创建和复制?还是我真的应该尝试解决这些问题?

My question is: is the compiler able to optimize this and skip the create and copy? Or should I really try to fix these occurrences?

供您参考...我们正在使用C ++ 14.

For your reference... we're working with C++14.

推荐答案

我的问题是:编译器是否能够优化此设置并跳过创建和复制?还是我应该尝试解决这些问题?

My question is: is the compiler able to optimize this and skip the create and copy? Or should I really try to fix these occurrences?

通常情况下,它无法避免复制.由于 emplace_back 通过转发引用来接受,因此它必须从纯标准角度创建临时文件.毕竟,这些引用必须绑定到对象.

It can't avoid a copy, in the general case. Since emplace_back accepts by forwarding references, it must create temporaries from a pure standardese perspective. Those references must bind to objects, after all.

复制省略是一组规则,允许避免使用复制(或移动)构造函数,并且消除了复制,即使该构造函数和相应的析构函数具有副作用也是如此.它仅在特定情况下适用.通过引用传递参数不是其中之一.因此,对于非平凡的类型,如果对象副本不能按as-if规则内联,则如果编译器的目标是符合标准,则束缚他们的双手.

Copy elision is a set of rules that allows a copy(or move) constructor to be avoided, and a copy elided, even if the constructor and corresponding destructor have side-effects. It applies in only specific circumstances. And passing arguments by reference is not one of those. So for non-trivial types, where the object copies can't be inlined by the as-if rule, the compiler's hands are bound if it aims to be standard conformant.

这篇关于在emplace()中创建对象时复制省略号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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