感谢我之前代码的一些有用且信息丰富的评论。现在我开始研究如何在我的代码中实现唯一指针。我想问一下我是否正确使用了唯一的指针。另外,我想知道如果我以这种方式使用唯一指针,我的代码是否会有效。到目前为止,我只观察到一旦超出范围,就会自动销毁这些唯一指针。使用唯一指针时还有哪些其他变体。我需要进一步解释如何在创建我自己的vector类的上下文中使用唯一指针。我的部分代码如下:
#include <iostream>
#include<memory>
template<typename S>
class MyVector{
private:
size_t size;
size_t capacity;
std::unique_ptr<S[]>a;
void allocate(){
capacity = size*2;
auto temp = std::make_unique<S[]>(capacity);
for(size_t i=0; i<this->getSize();++i){
temp[i]=std::move(a[i]);
}
}
public:
MyVector():size(0), capacity(1), a(new S[1]){};
size_t getSize(){return size;}
size_t getCapacity(){return capacity;}
void pushBack(S input){
++size;
if(this->getSize()==this->getCapacity()){
this->allocate();
}
a[this->getSize()-1]=input;
}
S &operator[](size_t p){return a[p];}
答案 0 :(得分:-1)
您的代码存在许多问题。下面,我解决了我在改进代码中发现的所有内容。
#include <iostream>
#include<memory>
template<typename S>
class MyVector
{
size_t m_size = 0; // use `size` as name for public member
size_t m_capacity = 0; // give default value
std::unique_ptr<S[]> m_data;
void grow_capacity()
{
m_capacity += m_capacity? m_capacity : 1;
auto temp = std::make_unique<S[]>(m_capacity);
for(size_t i=0; i!=m_size; ++i)
temp[i] = std::move(m_data[i]);
m_data = std::move(temp); //
}
public:
MyVector() = default; // let compiler work this out
size_t size() const noexcept // const member
{ return m_size; }
size_t capacity() const noexcept
{ return m_capacity; }
void pushBack(S const&input)
{
if(m_size == m_capacity) // only grow when needed
grow_capacity();
m_data[m_size++] = input;
}
void pushBack(S &&input) // version for moving in
{
if(m_size == m_capacity)
grow_capacity();
m_data[m_size++] = std::move(input);
}
S &operator[](size_t p)
{ return m_data[p]; }
S const &operator[](size_t p) const // const data access
{ return m_data[p]; }
};