且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何“返回对象"在 C++ 中?

更新时间:2022-01-13 01:06:39

我不想返回一个复制的值,因为它效率低下

I don't want to return a copied value because it's inefficient

证明它.

在 C++0x 移动语义中查找 RVO 和 NRVO.在 C++03 中的大多数情况下,out 参数只是让代码变得丑陋的好方法,而在 C++0x 中,使用 out 参数实际上是在伤害自己.

Look up RVO and NRVO, and in C++0x move-semantics. In most cases in C++03, an out parameter is just a good way to make your code ugly, and in C++0x you'd actually be hurting yourself by using an out parameter.

只需编写干净的代码,按值返回.如果性能是一个问题,请对其进行分析(停止猜测),然后找出可以解决的方法.它可能不会从函数返回东西.

Just write clean code, return by value. If performance is a problem, profile it (stop guessing), and find what you can do to fix it. It likely won't be returning things from functions.

也就是说,如果你对这样的写作一无所知,你可能想要使用 out 参数.它避免了动态内存分配,这更安全且通常更快.它确实要求您在调用函数之前有某种方法来构造对象,这并不总是对所有对象都有意义.

That said, if you're dead set on writing like that, you'd probably want to do the out parameter. It avoids dynamic memory allocation, which is safer and generally faster. It does require you have some way to construct the object prior to calling the function, which doesn't always make sense for all objects.

如果你想使用动态分配,至少可以把它放在一个智能指针中.(无论如何都应该这样做)然后你不用担心删除任何东西,事情是异常安全的,等等.唯一的问题是它可能比按值返回慢!

If you want to use dynamic allocation, the least that can be done is put it in a smart pointer. (This should be done all the time anyway) Then you don't worry about deleting anything, things are exception-safe, etc. The only problem is it's likely slower than returning by value anyway!