使用带有自定义相等运算符和STL的shared_ptr的问题

Cor*_*ius 1 c++ shared-ptr comparison-operators c++11

将共享指针与自定义相等运算符和std :: list一起使用时似乎存在问题.

我将以下示例代码放在一起以演示该问题.

在尝试编译之前:

我正在使用 gcc version 4.5.2 20110127

使用以下命令行:

g++ -g -O0 -std=gnu++0x test.cpp

如果未启用c ++ 0x功能,则源将无法编译.

#include<list>
#include<boost/shared_ptr.hpp>

using std::list;
using std::shared_ptr;
using std::cout;
using std::endl;

class TestInt
{
   public:
      TestInt(int x);
      bool operator==(const TestInt& other);

   private:
      int _i;
};

TestInt::TestInt(int x)
{
   _i = x;
}

bool
TestInt::operator==(const TestInt& other)
{
   if (_i == other._i){
      return true;
   }
   return false;
}

class Foo
{
   public:
      Foo(TestInt i);
      shared_ptr<TestInt> f(TestInt i);

   private:
      list<shared_ptr<TestInt>> _x;
};

Foo::Foo(TestInt i)
{
   _x.push_back(shared_ptr<TestInt>(new TestInt(i)));
};

shared_ptr<TestInt>
Foo::f(TestInt i)
{
   shared_ptr<TestInt> test(new TestInt(i));
   int num = _x.size();
   list<shared_ptr<TestInt>>::iterator it = _x.begin();
   for (int j=0; j<num; ++j){
      if (test == *it){
         return test;
      }
      ++it;
   }
   throw "Error";
}

int main(){
   TestInt ti(5);
   TestInt ti2(5);
   Foo foo(ti);
   foo.f(ti2);
   std::cout << "Success" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我本来期望代码完成Success但反而抛出.

插入一个*infront test*it修复问题,但我的理解是,当shared_ptr __a.get() == __b.get()在其==运算符中调用时,它应该使用自定义相等运算符TestInt.我不明白为什么不是.这是一个错误吗?

提前致谢.

Pup*_*ppy 10

这是因为当您比较两个时shared_ptr<T>,您正在比较引用,即两个实例指向的内存地址,而不是基础值.

  • shared_ptr :: get()返回指向引用对象的指针,而不是对它的引用.DeadMG的答案是正确的. (4认同)