对于 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标准要求,类型可以“赋值”,或者可以”拷贝“即可。
- 对于 std::vector<T> , 当T没有赋值运算符函数的时候,如何调用vector push_back?
- vector的push_back()函数的赋值方式
- vector的push_back对于拷贝构造和赋值操作的调用
- std::list<T> , std::vector<T> erase
- std::vector<T>的reserve()和resize()
- c++的赋值构造函数以及vector::push_back的问题
- std::vector<T>内存映像
- vector push_back 是否调用构造函数
- vector::push_back函数解析
- vector调用push_back() 内存泄露的风险
- vector<T>
- vector<const *T>, vector<*T>
- vector 的 push_back[转]
- vector的push_back
- C++ vector的push_back
- vector的push_back
- vector的大小sizeof(vector<T>)
- vector push_back
- linux select函数学习
- UTF-8带签名和无签名的区别
- module_init的加载和释放
- c# FTP操作
- MongoVUE 15天试用期解决办法-hengyunabc
- 对于 std::vector<T> , 当T没有赋值运算符函数的时候,如何调用vector push_back?
- Caliburn第1部分:入门
- 关于asp.net Session丢失问题的总结
- swf 多媒体流格式
- vc 编译的那些事儿
- 简单罗列一些JDK的变化
- Wap1.0基础
- CxImage
- String.Format格式说明