c++ - 将 shared_ptr 与自定义相等运算符和 STL 结合使用时出现问题

标签 c++ c++11 shared-ptr comparison-operators

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

我整理了以下示例代码来演示该问题。

在尝试编译之前:

我正在使用 gcc 版本 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;
}

我原以为代码会以 Success 结束,但它会抛出异常。

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

提前致谢。

最佳答案

这是因为当你比较两个 shared_ptr<T> ,您正在比较引用,即两个实例指向的内存地址,不是底层值。

关于c++ - 将 shared_ptr 与自定义相等运算符和 STL 结合使用时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5363501/

相关文章:

c++ - CustomDialogEx 的 shared_ptr 或 unique_ptr

C++ 类 API 方法返回临时可迭代物质的链接

c++ - 为什么 std::shared_ptr 不使用引用链接?

c++ - 一种从 .STL(立体光刻)文件计算质心的方法?

c++ - 我知道是什么导致了段错误,但为什么呢?

c++ - 显示 QDialog 框时的 QT 线程问题

c++ - 使用 DFS 进行后序打印

c++ - __LINE__ 在传递给类似函数的宏的 lambda 中计算不一致

c++ - 如何初始化用 auto 关键字声明的循环计数器?

c++ - 在 C++ 中将智能指针放入类数据(作为类成员)的正确方法是什么?