[英]Comparator operator in weak_ptr C++
我仍然是新stl成员的新手。任何人都可以指出为什么这段代码会给出分段错误?
#include<memory>
#include<stdio.h>
#include<map>
#include<set>
#include<string>
using namespace std;
struct StubClass
{
weak_ptr<string> b;
int c;
friend bool operator==(StubClass x,StubClass y);
friend bool operator<(StubClass x,StubClass y);
StubClass(weak_ptr<string> x):b(x){c=5;}
};
bool operator==(StubClass d,StubClass c) { return d.b==c.b;}
bool operator<(StubClass d,StubClass c) { return d.b<c.b; }
int main()
{
shared_ptr<string> spPtr(new string("Hello"));
weak_ptr<string> wpPtr(spPtr);
StubClass hello(wpPtr);
set<StubClass> helloSet;
helloSet.insert(hello);
if(helloSet.find(StubClass(wpPtr))!=helloSet.end()) printf("YAYA");
else puts("Bye");
}
错误符合
if(helloSet.find(StubClass(wpPtr))!= helloSet.end())printf(“YAYA”);
更多的研究表明,调用StubClass的比较器函数时会出现问题。 我在这里编译程序
编辑:
bool operator==(StubClass d,StubClass c) { return d.b.lock()==c.b.lock();}
bool operator<(StubClass d,StubClass c) { return d.b.lock()<c.b.lock(); }
这解决了这个问题。我应该阅读更多。:(无论如何,社区中的任何人都可以解释第一个代码给出SIGSEGV的原因。我最终想出来了,但仍然有一个很好的解释不会受到伤害。:)
您的原始代码段错误,因为您不小心设置了无限递归:
bool operator<(StubClass d,StubClass c) { return d.b<c.b; }
没有operator<
for weak_ptr
。 但是,您确实有从weak_ptr
到StubClass
的隐式转换。 StubClass
有一个operator<
。 所以这个函数无限地调用自己:因此是段错误。
来自inkooboo的当前接受的答案也将导致未定义的行为,可能导致崩溃。 由于weak_ptrs
在程序执行期间过期(比测试用例更复杂),因此它们的顺序将发生变化。 当在set
两个weak_ptrs
之间发生这种情况时,该set
将被破坏,可能导致崩溃。 然而,有一种方法可以使用owner_less
专门为此用例设计:
bool operator==(const StubClass& d, const StubClass& c)
{
return !owner_less<weak_ptr<string>>()(d.b, c.b) &&
!owner_less<weak_ptr<string>>()(c.b, d.b);
}
bool operator<(const StubClass& d, const StubClass& c)
{
return owner_less<weak_ptr<string>>()(d.b, c.b);
}
或者,如果您愿意,也可以使用成员函数owner_before
进行编码。 两者都是等价的:
bool operator==(const StubClass& d, const StubClass& c)
{
return !d.b.owner_before(c.b) && !c.b.owner_before(d.b);
}
bool operator<(const StubClass& d, const StubClass& c)
{
return d.b.owner_before(c.b);
}
使用这些函数,即使一个weak_ptr
到期而另一个没有,它们的顺序仍然稳定。 因此,你将有一个明确定义的set
。
如果你想比较存储在weak_ptr中的字符串,请执行以下操作:
bool operator<(StubClass d, StubClass c)
{
std::shared_ptr<std::string> a = d.b.lock();
std::shared_ptr<std::string> b = c.b.lock();
if (!a && !b)
return false;
if (!a)
return true;
if (!b)
return false;
return *a < *b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.