大佬教程收集整理的这篇文章主要介绍了C中的智能参考,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以在C中创建一个智能引用(对于特定的类,因为你不能重载.运算符),它具有与普通C引用相同的语义,但是在STL容器中使用时会重新设置?
例如,如果我有一些int_ref类,正常的整数运算符重载,构造和赋值如下所示:
class int_ref{ int * p; public: int_ref(int * ip) : p(ip) {} int_ref(const int_ref & other) : p(other.p) { /* maybe some refcounTing stuff here */ } int_ref & operator = (const int_ref & other){ if (!p) throw something_bad(); *p = *other.p; return *this; } void reseat(const int_ref & other){ p = other.p; } }
然后我不能将它与std :: vector一起使用,因为它不会重置引用,我不想要这样的事情:
std::vector<int_ref> vec; int_ref five = new int(5); vec.push_BACk(fivE); vec.push_BACk(new int(1)); std::sort(vec.begin(),vec.end()); // the value of five is Now 1
我可以使用右值引用使它与STL一起玩得很好,
int_ref & operator=(int_ref && other){ reseat(other); return *this; }
但是返回一个int_ref的函数会使用rvalue重载,我会得到这个:
int_ref make_number(){ return new int(10); } int_ref ref = new int(5); int_ref other = ref; other = make_number(); // instead of copying,as a reference would,// other Now points to something other than ref
因此,容器的元素在这方面不能模仿引用语义.如果你超载运算符&为了返回参考地址,然后例如违反了向量的连续存储保证,因为对于所有0< = n<< = n<< = n<< = n<< = n< v.size() boost :: addressof()是为解决这个问题而发明的,所以你不必使用&获取通用代码中对象的地址.但即使标准也懒得说静态< T *>(& static_cast< char&>(v [n]))而不是& v [n].即使您正在考虑使用它,也很难确定何时需要对象的实际地址,以及何时需要对象作者认为您想要的地址.最好永远不要超载一元运算符&.这意味着你将获得一个部分版本的引用语义,这可能会以自己的方式混淆.
以上是大佬教程为你收集整理的C中的智能参考全部内容,希望文章能够帮你解决C中的智能参考所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。