[英]C++ subscripting operator [] for a Vector class using unique pointers
I'm writing my own vector class using malloc
.我正在使用
malloc
。 In particular, to provide a minimial example I just show the constructor and the subscripting operator []
特别是,为了提供一个最小的例子,我只展示了构造函数和下标运算符
[]
#include <iostream>
#include <algorithm>
#include <utility>
#include <cstdlib>
template<typename T>
class Vector{
std::unique_ptr<T,decltype(&free)> elem{nullptr,free};
std::size_t _size{};
std::size_t _capacity{};
public:
Vector() = default;
~Vector(){
for(auto i = 0; i <_size; ++i){
// invoke the destructor
}
}
Vector(std::initializer_list<T> list): // pass by value
elem{static_cast<T*>(malloc(list.size()*sizeof(T))), free},
_size{list.size()},
_capacity{list.size()}{
std::uninitialized_copy(list.begin(), list.end(), elem.get());
}
auto& operator[](const std::size_t i){
return elem[i];
}
const auto& operator[](const std::size_t i) const{
return elem[i];
}
};
Then I implemented the classical push_back()
, but all the errors I got come from the following:然后我实现了经典的
push_back()
,但我得到的所有错误都来自以下:
error: no match for ‘operator[]’ (operand types are ‘const std::unique_ptr<int, void (*)(void*)>’ and ‘const size_t’ {aka ‘const long unsigned int’})
80 | return elem[i];
It seems that the problem is that I can't access the i
-th element of my unique_ptr
, but I really can't understant what's the problem!似乎问题在于我无法访问我的
unique_ptr
的第i
个元素,但我真的无法理解问题所在! How can I fix this, so that all the other functions I implemented work?我该如何解决这个问题,以便我实现的所有其他功能都可以工作? Also, what is the problem in my
elem[i]
is elem
is a unique_prt
?另外,我的
elem[i]
的问题是elem
是unique_prt
吗?
std::unique_ptr<T>
doesn't have operator[]
, but std::unique_ptr<T[]>
does. std::unique_ptr<T>
没有operator[]
,但std::unique_ptr<T[]>
有。
So you might use所以你可以使用
std::unique_ptr<T[], decltype(&free)> elem{nullptr,free};
Note: using class for deleter allows Empty Base Optimization (EBO), and simplify call site:注意:使用 class 作为删除器允许空基优化 (EBO),并简化调用站点:
struct Free
{
void operator()(void* p) const { free(p); }
};
std::unique_ptr<T[], Free> elem{nullptr};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.