我创建了自己的std :: vector,但是我生成了一个错误

时间:2018-04-01 22:12:06

标签: c++

我为T* data以及我的析构函数分配内存的方式有问题吗?请注意T* data已作为私人变量提供给我。我的终端中不断出现分段错误错误。另外,我收到以下警告:

unused variable 'data_' [-Wunused-variable] T* data_ = new T[size_];

这是我的代码:

public:
    // Define the iterator type to just be a pointer to T.
    typedef T* iterator;

    // Constructs an empty vector. Allocate an initial capacity of 1 element,
    // but do not add an element to the vector (i.e. capacity will be 1 while
    // size will be 0). You do not need to worry about bad_alloc exceptions.
    csc340_vector() {
        size_ = 0;
        capacity_ = 1;
        T* data_ = new T[size_];
    }

    // Destructs/de-allocates dynamic memory (if any was allocated).
    ~csc340_vector(){
       delete [] data_;
    }
private:
    T* data_;                // Storage for the elements
    unsigned int size_;      // Number of elements defined in the vector
    unsigned int capacity_;  // Number of elements that the vector can hold

};

另外,我尝试使用T* data_ = new T[capacity_];,但它仍会生成相同的未使用变量警告。

1 个答案:

答案 0 :(得分:3)

        T* data_ = new T[size_];

不是您的会员数据_。它是一个本地声明的变量。

使用您编写的成员

data_ = new T[size_];

或是否有歧义

this->data_ = new T[size_];