从C ++函数返回对象的正确方法是什么? [英] What is the proper way to return an object from a C++ function?

查看:195
本文介绍了从C ++函数返回对象的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感到困惑:


  • 返回对象函数中的变量,这消耗了内存)

  • 返回指针(但是你必须记住删除它,在调用代码中,

  • 返回引用(但这不可能,因为这将是对函数的局部变量的引用,一旦函数结束)

  • returning an object (but then the object is copied from the local variable in the function, which consumes memory)
  • returning a pointer (but then you have to remember to delete it, in the calling code, which is weird)
  • returning a reference (but this is not possible because this would be a reference to a local variable of the function, which would be deleted as soon as the function ends)

我正在寻找从C ++函数返回对象的正确方法,在基本C ++中(没有库处理指针和自动释放内存)。

I am looking for the proper way to return an object from a C++ function, in basic C++ (no library handling pointers and freeing memory automatically). I want to know how this is supposed to be done.

谢谢

推荐答案

现代编译器通常会实施(命名)返回值优化,通过它,您引用(并且逻辑上期望)的副本不会完成。

Modern compilers typically implement the (Named) Return Value Optimization, by which the copy you reference (and would logically expect) is not done.

自从Visual Studio 2005(VC ++ 8.0)以来,我不再三思考返回对象。

Ever since Visual Studio 2005 (VC++ 8.0) I don't think twice about returning objects.

这篇关于从C ++函数返回对象的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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