本文介绍了boost :: shared_ptr问题。为什么这个工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在尝试这个问题时,我创建了一个我完全不明白的示例。特别是,它强调了我对指针,引用和boost :: shared_ptr的误解。 int& r = *(new int(0)); //无偿指针泄漏,得到初始化它的东西 { 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 } cout<< * p =<< * p 运行此代码会产生如下输出: $ b b r = 100 r = 100 * p = 100 * p = 13 为什么引用在shared_ptr死亡后生存,但指针不存在? 在这里的答案有一个问题,似乎有两个完全相反和矛盾的解决方案,没有一致的是真相。我想在删除shared_ptr后使用引用,但如果它无效,我真的需要理解这一点。 也许有人可以发布一个简单的例子,因为 r = * sp; >不做你认为它做的。它分配到引用对象,即在第1行中在堆上创建的匿名 int 对象。不能在C ++中重新引用引用。 这是标准关于评估引用表达式的说法: 表达式最初具有类型 T 的引用,类型在任何之前调整为 T 进一步分析。 表达式指定由引用,表示的对象或函数,根据表达式,表达式是一个左值或一个x值。 所以你看,没有办法得到引用本身。 也许这段代码会更清楚: code> int a = 42; int b = 97; int& r = a; // r只是一个别名(另一个名字)为 r = b; //将b赋值给a(不会将r绑定到b,这在C ++中是不可能的) 执行最后一行, a 和 b 包含97,因为 r = b 表示 a = b 。 In experimenting with this question I created an example that I utterly do not understand. In particular, it highlights my misunderstanding of pointers, references, and the 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;Running this code gives an output something like this:r=100r=100*p=100*p=13Why does the reference survive the death of the shared_ptr but the pointer does not?There's a problem in the answers here in that there seem to be two diametrically opposed and contradictory solutions and no consensus upon which is the truth. I would like the ability to use a reference after a shared_ptr is deleted, but if it's invalid I really need to understand this.Perhaps someone can post a simple example that demonstrates the undefined behavior in the reference. 解决方案 Because r = *sp; does not do what you think it does. It assigns to the referent, that is, to the anonymous int object you created on the heap in line 1. You cannot reseat references in C++.Here is what the standard says about evaluating reference expressions: 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.So you see, there is no way to get to "the reference itself". It simply does not exist in C++.Maybe this code will make it clearer: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++!)After executing the last line, both a and b contain 97, because r = b really means a = b. 这篇关于boost :: shared_ptr问题。为什么这个工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-03 05:21