Do C ++编译器在通过值返回时避免复制? [英] Do C++ compilers avoid copying when returning by value?

查看:153
本文介绍了Do C ++编译器在通过值返回时避免复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  LargeObject getLargeObject()
{
LargeObject glo;
//做一些初始化东西glo
return glo
}

无效test()
{
LargeObject tlo = getLargeObject();
// do sth。与tlo;
}

一个简单的编译器会在getLargeObject然后在返回时在test()中将它分配给tlo,这涉及到一个复制操作。



但是一个聪明的编译器不应该知道glo将被分配给tlo因此只是使用tlo的内存首先避免复制操作?导致一些东西(功能上)像:

  void getLargeObject(LargeObject& lo)
{
/ / do init stuff
}

void test()
{
LargeObject lo;
getLargeObject(lo);
}

我的猜测是,编译器做类似的事情。但是它总是可以做到吗?有没有情况下,它不能像这样优化?我如何知道我的返回值是否被复制?

解决方案

你的猜测是正确的。是的,有些情况下它不能做,例如:

  LargeObject getLargeObject()
{
LargeObject glo1,glo2;
//做一些初始化的东西
if(rand()%2)
return glo1;
return glo2;
}

它不能在那里做,因为编译器不知道它是否将使用glo1或glo2作为返回值。



如何知道我的返回值是否被复制? >

我可以想到的两种方式。您可以创建嘈杂的复制构造函数。也就是说,复制具有一些可检测副作用的构造函数,如打印消息。然后当然有旧的看看大会。


Consider the following code:

LargeObject getLargeObject()
{
    LargeObject glo;
    // do some initialization stuff with glo
    return glo;
}

void test()
{
    LargeObject tlo = getLargeObject();
    // do sth. with tlo;
}

A simple compiler would create a local LargeObject glo on the getLargeObject() stack and then assign it to tlo in test() when returning, which involves a copy operation.

But shouldn't a clever compiler realize that glo is going to be assigned to tlo and thus just use tlo's memory in the first place to avoid the copy operation? Resulting in something (functionally) like:

void getLargeObject(LargeObject &lo)
{
    // do init stuff
}

void test()
{
    LargeObject lo;
    getLargeObject(lo);
}

My guess is, that compilers do something similar. But can it always be done? Are there situations where it can't be optimized like that? How can I know if my return value is copied or not?

解决方案

Your guess is correct. And yes, there are situations where it cannot be done, for example:

LargeObject getLargeObject()
{
    LargeObject glo1, glo2;
    // do some initialization stuff         
    if (rand() % 2)
        return glo1;
    return glo2;
}

It can't be done there because the compiler can't know whether it will use glo1 or glo2 for the return value.

"How can I know if my return value is copied or not?"

Two ways I can think of. You could create noisy copy constructors. That is, copy constructors that have some detectable side effect, like printing a message. Then of course there's the old look at the assembly.

这篇关于Do C ++编译器在通过值返回时避免复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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