清除std::vector对象需要赋值操作符.为什么
Clearing an std::vector needs an assignment operator. Why?
在我的应用程序中,我需要存储一小部分临时数据。在这个临时数据中,我想存储对另一个类的引用,因为它不能是nullptr,所以我使用引用。
是使用一个向量来存储数据(我没有太多的数据,所以向量是好的)。
填充vector并对其进行迭代可以正常工作,但清除vector似乎会产生问题。
这是一些显示问题的简化代码:
class Department
{
};
class Person
{
public:
Person (const Department &dept)
: m_dept(dept)
, m_salary(1000)
{}
private:
const Department &m_dept;
double m_salary;
};
#include <vector>
int main()
{
std::vector<Person> persons;
Department dept1;
Department dept2;
persons.push_back (Person(dept1));
persons.push_back (Person(dept2));
persons.clear();
}
除了最后一条语句外,所有语句都编译并运行良好。清除向量会给出以下错误信息(Visual Studio 2010):
C:DevStudioVs2010VCINCLUDExutility(2526) : error C2582: 'operator =' function is unavailable in 'Person'
C:DevStudioVs2010VCINCLUDExutility(2547) : see reference to function template nstantiation '_OutIt std::_Move<_InIt,_OutIt>(_InIt,_InIt,_OutIt,std::_Nonscalar_ptr_iterator_tag)' being compiled
with
[
_OutIt=Person *,
_InIt=Person *
]
C:DevStudioVs2010VCINCLUDEvector(1207) : see reference to function template instantiation '_OutIt std::_Move<Person*,Person*>(_InIt,_InIt,_OutIt)' being compiled
with
[
_OutIt=Person *,
_InIt=Person *
]
C:DevStudioVs2010VCINCLUDEvector(1190) : while compiling class template member function 'std::_Vector_iterator<_Myvec> std::vector<_Ty>::erase(std::_Vector_const_iterator<_Myvec>,std::_Vector_const_iterator<_Myvec>)'
with
[
_Myvec=std::_Vector_val<Person,std::allocator<Person>>,
_Ty=Person
]
test.cpp(21) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
with
[
_Ty=Person
]
原因似乎是std::vector::clear的实现调用std::vector::erase,后者调用_Move方法,似乎需要赋值操作符。
为什么clear方法不能简单地:
- 为vector 中的所有元素调用析构函数。
- 设置矢量大小为零
为什么会这样?
其他编译器也有这个问题吗?
任何放入vector中的类都需要一个拷贝赋值操作符(c++ 11中至少需要一个移动赋值操作符)。当你真正得到错误时,这只是一个实现质量问题
您是否真的注释掉了clear()调用,并尝试编译它?我很确定(我的编译器同意我的看法),push_back是导致这种情况的原因(由于需要复制现有数据)
相关文章:
- 赋值重载:为什么使用相同的对象会导致程序中出现问题
- c++中的重载赋值操作符
- c++类继承和赋值操作符
- 带引用类成员的赋值操作符
- 复制构造函数,赋值操作符重载
- c++派生类赋值操作符
- 通过调用Move赋值操作符实现Move构造函数
- 在类赋值操作符函数中,为什么必须返回*this ?
- 为什么不是只有一个?复制构造函数和赋值操作符
- 为什么这里需要构造函数和赋值操作符
- 清除std::vector对象需要赋值操作符.为什么
- 为什么std::weak_ptr没有move构造函数或move赋值操作符?
- Visual c++ 2010 / QT:为什么要调用类的赋值操作符
- 为什么赋值操作符用于深度复制,谁调用它
- (为什么)移动构造函数或移动赋值操作符应该清除其参数
- 为什么要在单例中删除move构造函数和move赋值操作符?
- 为什么我要将复制构造函数和赋值操作符设为私有并在c++中实现呢?
- 为什么需要在c++赋值操作符中删除已分配的内存?
- 为什么STL使用赋值操作符在容器中移动项?
- 为什么重载复合赋值操作符可以是非成员函数