在c ++中返回一个函数的引用 [英] Returning a reference from a function in c++

查看:137
本文介绍了在c ++中返回一个函数的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设我们已经得到了

  T * p; 

这个函数应该返回一个参考给 T 对象。但是它返回 * p ,所以它返回一个它指向的值。那么,如果我们写 T& operator ... T operator ...

  T&运算符*()const {
if(p)
return * p;
throw std :: runtime_error(unbound);
};

返回参考值和正常值之间有什么区别?


如果你返回一个值( T operator ... ),你将返回一个新的对象,一份 * p 的副本。如果调用者修改返回的对象,它不会影响你的属性变量。通过复制进行返回会产生成本(CPU操作会创建复制对象的复制+内存使用情况)。它还要求T是可疑的(提供一个有效的拷贝构造函数)。

如果你通过引用返回( T& operator ... ),您将返回对象的地址(最后,它与返回poinetr T * 非常相似,使用引用的语法与使用指针的语法不同)。如果调用者修改了返回的引用对象,它会影响你的属性变量(但是,使得返回的引用 const T& 会阻止这种情况)。



只要可以保证在调用者使用引用时引用的变量保持活动状态,引用是更可取的(就内存使用而言更快更好)。例如,如果你正在返回一个由该函数创建的本地对象,它必须通过复制而不是引用来返回)。



阅读更多:有什么区别指针变量和C ++中的引用变量?


I would like to ask about returning a pointer from function.

Assuming that we have got

T *p;

This function should return a refrence to a T object. But it returns *p so it returns an value that it is pointing to. So is there no difference if we will write T& operator... or T operator...?

   T& operator*() const{
        if(p)
            return *p;
        throw std::runtime_error("unbound");
    };

What is a difference between returning a reference and a value normally?

解决方案

If you return a value (T operator...), you will return a new object, a copy of *p. If caller modifies the returned object, it won't affect your attribute variable. Returning by copy has a cost (CPU operations to create the copy + memory usage of the copied object). It also requires T to be capiable (to provide a valid copy constructor).

If you return by reference (T& operator...), you will return the address of the object (in the end, it's very similar to returning a poinetr T*, it costs the same, only syntax to use references is different than syntax to use pointers). If caller modifies the returned referenced object, it will affect your attribute variable (however, making the reference returned const T& will prevent that).

Reference is preferable (faster and better in term of memory usage), as far as you can guarantee that the referenced variable remains alive while caller will use the reference. For instance, if you are returning a local object created by the function, it must be returned by copy, not by reference).

Read more here: What are the differences between a pointer variable and a reference variable in C++?

这篇关于在c ++中返回一个函数的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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