具有不同const正确性的向量赋值操作符

Assignment operator on vectors with different const correctness

本文关键字:向量 赋值操作符 正确性 const      更新时间:2023-10-16
我有一个非常简单的方法:
void SomeClass::GetListStuff(std::vector<Stuff const *> &listStuff) const
{   listStuff = m_listStuff;   }

其中m_listStuff是someeclass的成员,类型为

std::vector<Stuff *> 
这段代码给了我一个错误,说
there's no match for 'operator='
in 'listStuff = ((const SomeClass*)this)->SomeClass::m_listStuff

如果我从ListStuff指针中拿走const,它会工作得很好。我也可以在listStuff上调用insert()(不改变const的正确性),它可以工作。有人能解释一下原因吗?

我认为你应该这样做:

void SomeClass::GetListStuff(std::vector<Stuff*> &listStuff) const
{   
       listStuff = m_listStuff;   
}

也就是说,使用std::vector<Stuff*>而不是std::vector<Stuff const*>,因为我怀疑m_listStuff被声明为std::vector<Stuff*>。所以参数类型应该匹配。

我认为一个更好的方法是:

std::vector<Stuff*> SomeClass::GetListStuff() const
{   
       return m_listStuff; //return a copy!
}

或者更好的方法是公开迭代器:

std::vector<Stuff*>::const_iterator cbegin() const
{   
       return m_listStuff.cbegin(); //return const_iterator (C++11 only)
                                    //in C++03, you can use begin()
                                    //it will work same as cbegin()
}
std::vector<Stuff*>::const_iterator cend() const
{   
       return m_listStuff.cend(); //return const_iterator (C++11 only)       
                                  //in C++03, you can use end()
                                    //it will work same as cend()
}

自己编写非const版本