在我的应用程序中,我需要存储一小组临时数据。在这个临时数据中,我想存储对另一个类的引用,因为它不能是nullptr,所以我使用了一个引用。清除std :: 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:\DevStudio\Vs2010\VC\INCLUDE\xutility(2526) : error C2582: 'operator =' function is unavailable in 'Person'
C:\DevStudio\Vs2010\VC\INCLUDE\xutility(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:\DevStudio\Vs2010\VC\INCLUDE\vector(1207) : see reference to function template instantiation '_OutIt std::_Move<Person*,Person*>(_InIt,_InIt,_OutIt)' being compiled
with
[
_OutIt=Person *,
_InIt=Person *
]
C:\DevStudio\Vs2010\VC\INCLUDE\vector(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 ::矢量::擦除,它调用_Move方法,这似乎需要赋值运算符。
为什么不能明确方法简单:
- 调用析构函数为载体
- 设置矢量大小为零
有趣的所有元素是,当我使用std :: list代替std :: vector,代码编译正确。
这是为什么?
其他编译器也有这个问题吗?
作为附带说明,在C++的引用不能为空,并且不能被重新安置。除非你想要两个属性,你不应该使用它们。 –