编辑:Welp,我想这是一个可怕的想法.
是否可以在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].即使您正在考虑使用它,也很难确定何时需要对象的实际地址,以及何时需要对象作者认为您想要的地址.最好永远不要超载一元运算符&.这意味着你将获得一个部分版本的引用语义,这可能会以自己的方式混淆.