简体   繁体   English

c ++内存分配和重写向量类

[英]c++ memory allocation and rewriting the vector class

I'm doing an assignment in c++ where we have to rewrite the std::vector class that inherits from an abstract Container class. 我正在用c ++进行赋值,我们必须重写从抽象Container类继承的std :: vector类。 We have to write methods for 'Vector' such as begin(), end(), push_back(), etc... Many of the basic std::vector Member functions found here: http://www.cplusplus.com/reference/vector/vector/ 我们必须为“向量”编写方法,例如begin(),end(),push_back()等。许多基本的std :: vector成员函数可以在这里找到: http//www.cplusplus.com/参考/载体/载体/


My question is multi-faceted mainly because I am a beginner and the memory of computers is fascinating. 我的问题是多方面的,主要是因为我是一个初学者,并且计算机的记忆令人着迷。 Also, sorry if this question is super specific or has similar answers on here but I'm really stuck because this is the first time I've dealt with memory. 另外,很抱歉,如果这个问题是超级特定的,或者在这里有类似的答案,但是我真的很困惑,因为这是我第一次处理内存。


Here are my Container and Vector class implementations: 这是我的Container和Vector类的实现:

template <typename T> 
class Container {
    protected:
        T* elem;
        int cap;
    public:
        virtual T& operator[](int i) = 0;
        virtual int size() = 0;
        ~ Container() { delete[] elem; }
};

template <typename T>
class Vector: public Container<T> {
    protected:
        using Container<T>::elem;
        using Container<T>::cap;
    private:
        int sz;
    public:
        // constructors
        Vector(); // default constructor
        Vector(int n); // fill constructor #1
        Vector(int n, T fill_val); // fill constructor #2
/*      // ~ Vector(); // destructors
unsure if the above is correct, because of the Container destructor                                
*/  
        // overloaded operators
        T& operator[](int i); // subscript overloading '[]'
        T& operator=(const Vector<T>& V); // assignment overloading '='
        // access methods
        T& front(); //returns a reference to the first element
        T& back(); //returns a reference to the last element
        // iterator methods
        T* begin(); // returns memory address of the first element
        T* end(); // returns memory address at the end
        // size methods
        int size() { return sz; }
        int capacity() { return cap; }
};

Part 2. 第2部分。

When/why do I need the destructor? 什么时候/为什么需要析构函数? I've tried to read up on destructors on Stack, but I feel more confused than clarified. 我试图阅读Stack上的析构函数,但我感到比澄清更困惑。 I'm assuming the SegFault is coming from memory needing to be deallocated, and I know I'm supposed to be learning how to dynamically allocate memory with this assignment. 我假设SegFault来自需要释放的内存,并且我知道我应该学习如何通过此分配动态分配内存。 The constructors and destructors are crucial for this process but can someone break it down as simply as possible for me? 构造函数和析构函数对于此过程至关重要,但是有人可以对我尽可能简单地分解它吗?


EDIT: 编辑:

I've fixed the segmentation fault by implementing Fureeish's answer. 我通过实施Fureeish的答案解决了细分错误。 My code has been updated above. 我的代码已在上面更新。

The only remaining inquiry is to the destructor and its purpose. 唯一剩下的询问是对销毁者及其目的的询问。 Do I need to implement one for Vector or will it be called automatically by Container ? 我是否需要为Vector实现一个,否则Container会自动调用它吗?

You decided to manage the memory by yourself, but you never allocated any. 您决定自己管理内存,但从未分配任何内存。 You're missing some new s here and there. 您在这里和那里都缺少一些new For example, given a: 例如,给定一个:

Vector(int n, T fill_val) {
    sz = n;
    cap = 2*n;
    for(int i = 0; i < sz; i++) {
        elem[i] = fill_val; 
    }
}

the for() loop iterates over elem , which is an uninitialized pointer. for()循环遍历elemelem是未初始化的指针。 You treat it like a pointer to a dynamically allocated array, but it simply points to some garbage value. 您将其视为指向动态分配数组的指针,但是它只是指向一些垃圾值。 Remember - first allocate, then work on ( only when you decide to manage the memory yourself. Typically you should prefer using standard implementations). 记住-首先分配,然后继续( 当您决定自己管理内存时。通常,您应该更喜欢使用标准实现)。

The correct version should look like this: 正确的版本应如下所示:

Vector(int n, T fill_val) {
    sz = n;
    cap = 2*n;
    elem = new T[cap]; // or cap-1, depending on what you do with `end()`.
    for(int i = 0; i < sz; i++) {
        elem[i] = fill_val; 
    }
}

The fact that you never encountered this problem while using other constructors is just you being extremely lucky and undefined behavior being sneaky 您在使用其他构造函数时从未遇到此问题的事实只是您非常幸运,而且未定义的行为是偷偷摸摸的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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