【发布时间】:2011-04-03 05:41:27
【问题描述】:
我一生都无法弄清楚这段代码有什么问题:
ClassA & doSomething (std::set<boost::shared_ptr<ClassB const> const > const & someSet)
{
std::set<boost::shared_ptr<ClassB> > secondSet;
for (std::set<boost::shared_ptr<ClassB const> const >::const_iterator it = someSet.begin(); it != someSet.end(); it++)
{
if (checkSomething(*it))
secondSet.insert(boost::const_pointer_cast<ClassB>(*it));
}
}
当我尝试编译时,我在 g++ 的第 4 行(for 循环的开头)收到以下错误:
/usr/include/c++/4.4/ext/new_allocator.h:79: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(const _Tp&) const [with _Tp = const boost::shared_ptr<const ClassB>]’ cannot be overloaded
/usr/include/c++/4.4/ext/new_allocator.h:76: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(_Tp&) const [with _Tp = const boost::shared_ptr<const ClassB>]’
如果我将 std::set 声明更改为包含非 const boost::shared_ptr,则代码可以完美编译,但这意味着我将无法在我的代码中强制执行 const 正确性。
有没有人知道可能导致这些错误的原因?我搜索了 Google 和 StackOverflow 都没有任何运气。
这是一个最小(非)工作示例:
#include <set>
#include <boost/shared_ptr.hpp>
class ClassB;
class ClassA
{
public:
ClassA & doSomething (std::set<boost::shared_ptr<ClassB const> const > const & someSet);
};
ClassA & doSomething (std::set<boost::shared_ptr<ClassB const> const > const & someSet)
{
std::set<boost::shared_ptr<ClassB> > secondSet;
for (std::set<boost::shared_ptr<ClassB const> const >::const_iterator it = someSet.begin(); it != someSet.end(); it++)
{
if (checkSomething(*it))
secondSet.insert(boost::const_pointer_cast<ClassB>(*it));
}
return (*this);
}
【问题讨论】:
-
这不是“例外”。这是一个编译错误
标签: c++