微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C中的智能参考

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐