What is the proper way to return an object from a C++ function?(从 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++ 函数返回对象的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C++ 函数返回对象的正确方法是什么?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30