Wil*_*mKF 3 c++ gcc const stdvector assignment-operator
如何将push_back()转换为C++ std :: vector而不使用默认定义违反const成员的operator =()?
struct Item {
Item(int value)
: _value(value) {
}
const char _value;
}
vector<Item> items;
items.push_back(Item(3));
Run Code Online (Sandbox Code Playgroud)
我想保留_value const,因为它在构造对象后不应该改变,所以问题是如何在不调用operator =()的情况下用元素初始化我的向量?
这是g ++ v3.4.6给我的基本错误:
.../3.4.6/bits/vector.tcc: In member function `Item& Item::operator=(const Item&)':
.../3.4.6/bits/vector.tcc:238: instantiated from `void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = Item, _Alloc = std::allocator<Item>]'
.../3.4.6/bits/stl_vector.h:564: instantiated from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Item, _Alloc = std::allocator<Item>]'
item.cpp:170: instantiated from here
.../3.4.6/bits/vector.tcc:238: error: non-static const member `const char Item::_value', can't use default assignment operator
Run Code Online (Sandbox Code Playgroud)
Die*_*ühl 12
因为std::vector<T>元素必须是可分配的.您键入的内容不是可分配的.一个实现.std::vector<T>可以避免坚持这个要求,但这将是一个损害,因为结果代码将不可移植.
您可以使用std::list<T>替代或更改您键入的定义.例如,您可以创建一个只读取值但不读取setter的访问器.当然,任务会改变价值.因此,选择是允许这种改变还是允许将对象放入容器中.你不会两者都得到.
| 归档时间: |
|
| 查看次数: |
2765 次 |
| 最近记录: |