编译器能否删除以下副本? [英] Can the compiler elide the following copy?

查看:138
本文介绍了编译器能否删除以下副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是一个菜鸟程序员,我知道过早的优化是坏的,但我也知道,复制巨大的东西在周围是坏的。

I'm still a rookie programmer, I know that premature optimization is bad, but I also know that copying huge stuff around is bad, as well.

我've read up on copy elision,它是同义词,但是维基百科上的例子使我觉得复制elision只能发生,如果被返回的对象在被完全构建的同时被返回。

I've read up on copy elision and it's synonyms but the examples on Wikipedia for example make it seem to me that copy elision can only take place if the object to be returned gets returned at the same time it gets completely constructed.

像向量这样的对象,当用作返回值时,通常只有在填充了某些东西时才有意义。
毕竟,一个空向量可以手动实例化。

What about objects like vectors, which usually only make sense when filled with something, when used as a return value. After all, an empty vector could just be instantiated manually.

那么,它也可以在这样的情况下工作?

So, does it also work in a case like this?

糟糕的风格简洁:

vector<foo> bar(string baz)
{
    vector<foo> out;
    for (each letter in baz)
        out.push_back(someTable[letter]);

    return out;
}

int main()
{
     vector<foo> oof = bar("Hello World");
}



我没有使用bar(vector& out,string text) ,但上述方法看起来会更好,美观和意图。

I have no real trouble using bar(vector & out, string text), but the above way would look so much better, aesthetically, and for intent.

推荐答案


例如wikipedia例如使我觉得复制elision只能发生,如果被返回的对象被返回的同时它被完全构造。

the examples on wikipedia for example make it seem to me that copy elision can only take place if the object to be returned gets returned at the same time it gets completely constructed.

这是误导(读:错)。问题是在所有代码路径中只返回一个对象,即只有一个构造的潜在返回对象正在发生。

That is misleading (read: wrong). The issue is rather that only one object is returned in all code paths, i.e. that only one construction for the potential return object is happening.

您的代码很好,任何现代编译器都可以复制该副本。

Your code is fine, any modern compiler can elide the copy.

另一方面,以下代码可能会产生问题: p>

On the other hand, the following code could potentially generate problems:

vector<int> foo() {
    vector<int> a;
    vector<int> b;
    // … fill both.
    bool c;
    std::cin >> c;
    if (c) return a; else return b;
}

这里,编译器需要完全构造两个不同的对象, > later 决定它们中的哪一个被返回,因此它必须复制一次,因为它不能直接在目标内存位置构造返回的对象。

Here, the compiler needs to fully construct two distinct objects, and only later decides which of them are returned, hence it has to copy once because it cannot directly construct the returned object in the target memory location.

这篇关于编译器能否删除以下副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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