對於 std::vector , 當T沒有賦值運算符函數的時候,如何調用vector push_back?

這個問題是在stackoverflow發現的:

http://stackoverflow.com/questions/12908398/can-placement-new-and-vectordata-be-used-to-replace-elements-in-a-vector

我是對討論做一個整理,如下。

1.代碼片段

#include <iostream>
  2 #include <vector>
  3 
  4 struct A
  5 {
  6     const int _i;
  7     A(const int &i):_i(i) {}
  8 };
  9 
 10 int main() {
 11     std::vector<A> vec;
 12     A c1(1);
 13     A c2(2);
 14 
 15     vec.push_back(c1);
 16     std::cout << vec[0]._i << std::endl;
 17 
 18     std::cout << vec[0]._i << std::endl;
 19 
 20     return 0;
 21 }

 

2.問題
如代碼中所示,struct A包含一個常量成員,作者想把 A類型的對象保存在 STL vector中,在GCC 4.2.4上編譯會報錯。錯誤信息如下,
root@VM-Ubuntu203001:~/test# g++ const_type.cpp 
const_type.cpp: In member function 'A& A::operator=(const A&)':
const_type.cpp:13: instantiated from 'void std::vector<_Tp,_Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typenamestd::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp,_Alloc> >, const _Tp&) [with _Tp = A, _Alloc =std::allocator<A>]'
/usr/include/c++/4.2/bits/stl_vector.h:605: instantiated from 'voidstd::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = A, _Alloc= std::allocator<A>]'
const_type.cpp:23: instantiated from here
const_type.cpp:13: error: non-static const member 'const int A::_i', can't usedefault assignment operator
/usr/include/c++/4.2/bits/vector.tcc: In member function 'voidstd::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typenamestd::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer,std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = A, _Alloc =std::allocator<A>]':
/usr/include/c++/4.2/bits/vector.tcc:256: note: synthesized method 'A&A::operator=(const A&)' first required here 

3.原因
在c++2003標準中,std::vector 要求保存的類型要可以調用”拷貝構造函數“和”賦值運算符函數”。
4.解決辦法
1、不要在類中用const 成員
2、不要企圖在vector中,使用含有const成員的類型
3、使用支持C++2011標準的編譯器,C++2011標準要求,類型可以“賦值”,或者可以”拷貝“即可。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章