简体   繁体   中英

C++ subscripting operator [] for a Vector class using unique pointers

I'm writing my own vector class using 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:

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! 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 ?

std::unique_ptr<T> doesn't have operator[] , but std::unique_ptr<T[]> does.

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:

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM