相信返回值优化

发布于 2024-08-18 16:23:51 字数 137 浏览 3 评论 0原文

您如何使用返回值优化
在某些情况下,我可以信任现代编译器使用优化,还是应该始终采用安全的方式并返回某种类型的指针/使用引用作为参数?

是否存在无法进行返回值优化的已知情况? 在我看来,编译器执行返回值优化相当容易。

How do you go about using the return value optimization?
Is there any cases where I can trust a modern compiler to use the optimization, or should I always go the safe way and return a pointer of some type/use a reference as parameter?

Is there any known cases where the return value optimization cant be made?,
Seems to me that the return value optimization would be fairly easy for a compiler to perform.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北方的巷 2024-08-25 16:23:51

每当启用编译器优化(在大多数编译器中,即使优化禁用),RVO 就会发生。 NRVO 不太常见,但大多数编译器也会执行此优化,至少在启用优化时是如此。

你是对的,编译器执行优化相当容易,这就是编译器几乎总是这样做的原因。唯一“无法实现”的情况是优化不适用的情况:RVO 仅在您返回未命名的临时对象时适用。如果你想返回一个命名的局部变量,可以使用 NRVO,虽然编译器实现起来稍微复杂一些,但它是可行的,而且现代编译器对此没有任何问题。

Whenever compiler optimizations are enabled (and in most compilers, even when optimizations are disabled), RVO will take place. NRVO is slightly less common, but most compilers will perform this optimization as well, at least when optimizations are enabled.

You're right, the optimization is fairly easy for a compiler to perform, which is why compilers almost always do it. The only cases where it "can't be made" are the ones where the optimization doesn't apply: RVO only applies when you return an unnamed temporary. If you want to return a named local variable, NRVO applies instead, and while it is slightly more complex for a compiler to implement, it's doable, and modern compilers have no problem with it.

似梦非梦 2024-08-25 16:23:51

为了最有可能发生这种情况,您可以返回一个直接在 return 语句中构造的对象 [谁能记住这个习惯用法的名称 - 我忘记了]:

Foo f() {
    ....
    return Foo( ... );
}

但与所有优化一样,编译器始终可以选择不这样做做吧。归根结底,如果您需要返回一个值,除了信任编译器之外别无选择 - 指针和引用不会解决这个问题。

To have the best chance that it occurs, you can return an object constructed directly in the return statement [can anyone remember the name for this idiom - I've forgotten it]:

Foo f() {
    ....
    return Foo( ... );
}

But as with all optimisations, the compiler can always choose not to do it. And at the end of the day, if you need to return a value thee is no alternative to trusting the compiler - pointers and references won't cut it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文