【问题标题】:C++ subscripting operator [] for a Vector class using unique pointers使用唯一指针的 Vector 类的 C++ 下标运算符 []
【发布时间】:2021-03-17 16:51:04
【问题描述】:

我正在使用malloc 编写自己的矢量类。特别是,为了提供一个最小的示例,我只展示了构造函数和下标运算符[]

#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];
  }
  
  
  
};

然后我实现了经典的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];

问题似乎是我无法访问我的unique_ptri-th 元素,但我真的无法理解问题所在!我该如何解决这样,我实现的所有其他功能都可以工作吗?另外,我的elem[i] 中的问题是elemunique_prt 吗?

【问题讨论】:

  • 显示的代码显然是在错误的概念下运行的,即unique_ptr 是某种具有重载[] 运算符的类数组对象?不是那样的。 elemstd::unique_ptr。为了使elem[i] 工作std::unique_ptr 需要重载[] 运算符。它没有。
  • @SamVarshavchik 我明白你的意思。但是我怎样才能使我的std::unique_prt 具有[] 运算符?
  • 您的意思是存储在您的std::unique_ptr 中的指针?使用其get() 方法检索存储的指针,并在其上使用[] 运算符。
  • @SamVarshavchik 喜欢elem.get()[i]?
  • 哦,您还必须在声明中添加括号:std::unique_ptr&lt;T[], ...

标签: c++ vector malloc smart-pointers unique-ptr


【解决方案1】:

std::unique_ptr&lt;T&gt; 没有operator[],但std::unique_ptr&lt;T[]&gt; 有。

所以你可以使用

std::unique_ptr<T[], decltype(&free)> elem{nullptr,free}; 

注意:使用删除器类允许空基优化(EBO),并简化调用站点:

struct Free
{
    void operator()(void* p) const { free(p); }
};


std::unique_ptr<T[], Free> elem{nullptr}; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 2012-03-11
    相关资源
    最近更新 更多