对于 std::vector<T> , 当T没有赋值运算符函数的时候,如何调用vector push_back?

来源:互联网 发布:dwg加密软件 编辑:程序博客网 时间:2024/05/18 08:09

这个问题是在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标准要求,类型可以“赋值”,或者可以”拷贝“即可。
原创粉丝点击