gpt4 book ai didi

c++ - C++ 中的智能引用

转载 作者:太空狗 更新时间:2023-10-29 20:17:10 24 4
gpt4 key购买 nike

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

是否可以在 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 的函数会使用右值重载,我会得到这个:

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

有解决办法吗?总的来说,这只是一个糟糕的想法吗?

最佳答案

尝试这样做的一个问题是 operator& .作为引用,它为您提供了被引用对象的地址(因为引用没有地址)。但是,对于容器的元素,它应该为您提供元素的地址(因为它们确实有地址)。

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

boost::addressof()被发明来解决这个问题,所以你不必使用 &在通用代码中获取对象的地址。不过连标准都懒得说static_cast<T*>(&static_cast<char&>(v[n]))而不是 &v[n] .即使在考虑使用它时,也很难决定何时需要对象的实际地址,以及何时需要对象作者认为您需要的地址。最好永远不要重载一元 operator& .这意味着您将获得部分版本的引用语义,这可能会以其自身的方式造成混淆。

关于c++ - C++ 中的智能引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7457296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com