2011-10-11 112 views
5

在我的應用程序中,我需要存儲一小組臨時數據。在這個臨時數據中,我想存儲對另一個類的引用,因爲它不能是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,代碼編譯正確。

這是爲什麼?

其他編譯器也有這個問題嗎?

+1

作爲附帶說明,在C++的引用不能爲空,並且不能被重新安置。除非你想要兩個屬性,你不應該使用它們。 –

回答

11

放在一個向量的任何類需要一個拷貝賦值運算符(或至少一招分配運算符在C++ 11中)。這只是實際發生錯誤時的實施質量問題。

2

你有沒有實際評論過clear()調用,並試圖編譯它? ,我敢肯定(和我的編譯器,我同意),該的push_back是造成這種(因現有數據的需要複製)

+0

該錯誤消息表示,它需要在'erase'這很可能是從'clear'稱爲('清楚=擦除(開始,結束)')。儘管賦值可能不會用於擦除所有內容,但函數仍需編譯。無論如何,可分性是一個容器要求。 - 我猜想,push_back可以通過複製構造函數來實現。 – visitor

+0

當評論清晰的通話時,一切正常。 – Patrick