2011-03-23 60 views
2

我有AA功能,基本上可以归结为这个(即我与挣扎的部分,忽略了实际发生的事情)删除的shared_ptr <const T>

class CellSorter 
{ 
public: 
    bool operator()(std::shared_ptr<const Cell> a, 
        std::shared_ptr<const Cell> b) const 
    { 
     return ((a->GetY() < b->GetY()) || 
       (a->GetY() == b->GetY() && 
        a->GetX() < b->GetX())); 
    } 
}; 
typedef std::set<std::shared_ptr<Cell>, CellSorter> Container; 
MyClass::Container MyClass::DoSomething(std::shared_ptr<const Cell> c) 
{ 
    MyClass::Container N; 
    // assume that this code works to copy some stuff to N, blah blah blah 
    std::remove_copy_if(_grid.begin(), _grid.end(), 
         std::inserter(N, N.begin()), 
         std::not1(CellIsNeighbor(c->GetX(), c->GetY()))); 
    N.erase(c); // ERROR 
    return N; 
}; 

的问题是,海湾合作委员会给我一个错误:

/usr/include/c++/4.4/bits/shared_ptr.h:651: error: invalid conversion from ‘const Cell*’ to ‘Cell*’

我认为这不应该被铸造的对象“C”从shared_ptr<const Cell>shared_ptr<Cell>,但不知何故,它是。我想让c指向一个常量单元,因为不需要修改它。而CellSorter不应该对const有问题。

任何想法为什么我不能做到这一点或如何解决它?

回答

2

这是因为容器中的shared_ptr的类型为std::shared_ptr<Cell>。您正在将std::shared_ptr<const Cell>传递给erase()方法。不同种类。您可以通过删除const限定符来修复它。

显然你也可以在这种情况下使用std::const_pointer_cast

http://msdn.microsoft.com/en-us/library/bb982336.aspx

+0

好的,所以答案是,我不能那样做。快速的问题,这是否也适用于常规指针?所以如果我的代码有一个'std :: set 容器',并且我有一个变量'const Cell * c',那么我仍然不能'container.erase(c)'?对我来说,这似乎很奇怪,因为我想保持'c'的常量正确性,我所做的不应该修改它。 – Matt 2011-03-23 06:03:07

+0

使用常规指针可以使用const_cast去除c的常量。但我不确定这是一个值得做的折中。我宁愿使用shared_ptr来管理内存,而不用担心在可能不合理的情况下保留const。 – Sean 2011-03-23 06:06:10

+0

好的,是的,我坚持shared_ptr,它更多的是好奇心。它看起来像我应该能够传递一个const指针(或智能指针)来设置::擦除,即使该集合包含非const指针(或智能指针)。但是,嘿,我可以忍受在这种情况下放弃const。 – Matt 2011-03-23 06:13:28

相关问题