了解返回值优化和返回临时值 - C ++ [英] Understanding return value optimization and returning temporaries - C++

查看:204
本文介绍了了解返回值优化和返回临时值 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这三个函数。

std::string get_a_string()
{
    return "hello";
}

std::string get_a_string1()
{
    return std::string("hello");
}

std::string get_a_string2()
{
    std::string str("hello");
    return str;
}




  1. RVO适用于所有三种情况?

  2. 是否可以返回上述代码中的临时项?我相信这是正常的,因为我通过价值返回它,而不是返回任何参考。

任何想法?

Any thoughts?

推荐答案

在第一种情况下,会进行RVO优化。 RVO是旧的功能,大多数编译器支持它。最后一种情况是所谓的NRVO(命名RVO)。这是C ++的相对新的特性。标准允许,但不需要实施NRVO(以及RVO),但有些编译器支持它。

In two first cases RVO optimization will take place. RVO is old feature and most compilers supports it. The last case is so called NRVO (Named RVO). That's relatively new feature of C++. Standard allows, but doesn't require implementation of NRVO (as well as RVO), but some compilers supports it.

您可以在Scott的第20项中阅读更多关于RVO Meyers的书 更有效的C ++。

You could read more about RVO in Item 20 of Scott Meyers book More Effective C++. 35 New Ways to Improve Your Programs and Designs.

这里是关于Visual C ++ 2005中的NRVO的一篇好文章。

Here is a good article about NRVO in Visual C++ 2005.

这篇关于了解返回值优化和返回临时值 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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