首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++中的智能引用

C++中的智能引用
EN

Stack Overflow用户
提问于 2011-09-18 03:36:56
回答 2查看 4.2K关注 0票数 3

编辑:好吧,我想这是个糟糕的主意。

是否可以在C++中进行智能引用(对于特定的类,因为您不能重载。运算符)具有与普通C++引用相同的语义,但是在STL容器中使用时会重新拔插哪一个?

例如,如果我有一些重载了普通整数操作符的int_ref类,构造和赋值如下所示:

代码语言:javascript
复制
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中使用它,因为它不会重新放置引用,而且我不想要这种东西:

代码语言:javascript
复制
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配合得很好,

代码语言:javascript
复制
int_ref & operator=(int_ref && other){
    reseat(other);
    return *this;
}

但是,返回int_ref的函数将使用右值重载,我得到的结果如下:

代码语言:javascript
复制
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

有什么办法可以解决这个问题吗?总的来说,这只是一个糟糕的想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-18 04:23:57

尝试这样做的一个问题就是operator&。对于引用,它会给出被引用对象的地址(因为引用没有地址)。但是,对于容器的一个元素,它应该给出该元素的地址(因为这些地址是有地址的)。

因此,容器的元素不能在这方面模仿引用语义。例如,如果重载operator&以返回被引用对象的地址,则违反了vector的连续存储保证,因为它显示&v[n] == &v[0] + n for all 0 <= n < v.size()

boost::addressof()就是为了解决这个问题而发明的,这样您就不必使用&在泛型代码中获取对象的地址。但即使是该标准也懒得说static_cast<T*>(&static_cast<char&>(v[n]))而不是&v[n]。即使您正在考虑使用它,也很难决定何时需要对象的实际地址,以及何时需要对象的作者认为您想要的地址。最好不要重载一元operator&。这意味着你将得到引用语义的部分版本,这可能会以它自己的方式令人困惑。

票数 4
EN

Stack Overflow用户

发布于 2011-09-18 04:22:16

您可能想要使用容器{boost:ptr_}。

您将指针存储在容器中(容器获得所有权)。但是当访问对象时,你会得到对对象的引用,而不是指针。

代码语言:javascript
复制
#include <boost/ptr_container/ptr_vector.hpp>

int main()
{
     boost::ptr_vector<int>    data;
     data.push_back(new int(5));


     std::cout << data[0] << "\n";  // Prints 5 as you get a reference to the object.
}

或者,如果你只是想要引用。然后您可以使用boost:ref

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7457296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档