gpt4 book ai didi

c++ - boost::shared_ptr 问题。为什么这行得通?

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

在试验 this question我创建了一个我完全不理解的示例。特别是,它强调了我对指针、引用和 boost::shared_ptr 的误解。

int& r = *(new int(0));//gratuitous pointer leak, got to initialize it to something
{
boost::shared_ptr<int> sp(new int(100));
r = *sp;
cout << "r=" << r << endl;
}
cout << "r=" << r << endl << endl;

int* p;
{
boost::shared_ptr<int> sp(new int(100));
p = &*sp;
cout << "*p=" << *p << endl;
}
cout << "*p=" << *p << endl;

运行这段代码会得到如下输出:

r=100
r=100

*p=100
*p=13

为什么引用在 shared_ptr 死亡后仍然存在,而指针却没有?


这里的答案有一个问题,似乎有两个截然相反和矛盾的解决方案,并且没有就哪个是事实达成共识。我希望能够在删除 shared_ptr 后使用引用,但如果它无效,我真的需要理解这一点。

也许有人可以发布一个简单示例来演示引用中的未定义行为。

最佳答案

因为 r = *sp; 并没有按照您的想法去做。它分配给引用对象,即分配给您在第 1 行中在堆上创建的匿名 int 对象。您不能在 C++ 中重新设置引用。

以下是标准关于评估引用表达式的内容:

If an expression initially has the type "reference to T", the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

所以你看,没有办法到达“引用本身”。它根本不存在于 C++ 中。

也许这段代码会更清楚:

int a = 42;
int b = 97;

int&r = a; // r is just an alias (another name) for a
r = b; // assigns b to a (does NOT bind r to b, that's impossible in C++!)

执行最后一行后,ab都包含97,因为r = b真正的意思是a = b.

关于c++ - boost::shared_ptr 问题。为什么这行得通?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390112/

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