C++ 中的引用让我感到困惑.:)
References in C++ are baffling me. :)
基本思想是我试图从函数返回一个对象.如果可能的话,我想不返回指针(因为那样我必须手动delete
它)并且不调用复制构造函数(为了效率,自然添加: 也是因为我想知道我是否无法避免编写复制构造函数).
The basic idea is that I'm trying to return an object from a function. I'd like to do it without returning a pointer (because then I'd have to manually delete
it), and without calling the copy-constructor, if possible (for efficiency, naturally added: and also because I wonder if I can't avoid writing a copy constructor).
总而言之,以下是我发现的执行此操作的选项:
So, all in all, here are the options for doing this that I have found:
MyClass fun() { ... }
) 或对类的引用 (MyClass& fun() { ...}
).return MyClass(a,b,c);
) 或返回现有变量 (MyClass x(a,b,c); return x;
).MyClass x = fun();
或 MyClass& x = fun();
)MyClass x = fun();
) 或将其分配给现有变量 (MyClass x; x =fun();
)MyClass fun() { ... }
) or a reference to the class (MyClass& fun() { ... }
).return MyClass(a,b,c);
) or return an existing variable (MyClass x(a,b,c); return x;
).MyClass x = fun();
or MyClass& x = fun();
)MyClass x = fun();
) or assign it to an existing variable (MyClass x; x = fun();
)还有一些想法:
MyClass&
似乎是一个坏主意,因为这总是导致变量在返回之前被销毁.MyClass&
because that always results in the variable being destroyed before it gets returned.这些结果太不一致了,我感到完全困惑.那么,这里究竟发生了什么?我应该如何正确构造和从函数返回一个对象?
These results are so inconsistent that I feel totally confused. So, what EXACTLY is happening here? How should I properly construct and return an object from a function?
理解 C++ 中的复制的最好方法通常是不要尝试生成一个人工示例并对其进行检测 - 允许编译器删除和添加复制构造函数电话,或多或少,因为它认为合适.
The best way to understand copying in C++ is often NOT to try to produce an artificial example and instrument it - the compiler is allowed to both remove and add copy constructor calls, more or less as it sees fit.
底线 - 如果您需要返回一个值,请返回一个值,不要担心任何费用".
Bottom line - if you need to return a value, return a value and don't worry about any "expense".
这篇关于C++:通过引用返回和复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!