在我的應用程序中,我需要存儲一小組臨時數據。在這個臨時數據中,我想存儲對另一個類的引用,因爲它不能是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++的引用不能爲空,並且不能被重新安置。除非你想要兩個屬性,你不應該使用它們。 –