簡體   English   中英

c ++內存分配和重寫向量類

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

我正在用c ++進行賦值,我們必須重寫從抽象Container類繼承的std :: vector類。 我們必須為“向量”編寫方法,例如begin(),end(),push_back()等。許多基本的std :: vector成員函數可以在這里找到: http//www.cplusplus.com/參考/載體/載體/


我的問題是多方面的,主要是因為我是一個初學者,並且計算機的記憶令人着迷。 另外,很抱歉,如果這個問題是超級特定的,或者在這里有類似的答案,但是我真的很困惑,因為這是我第一次處理內存。


這是我的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; }
};

第2部分。

什么時候/為什么需要析構函數? 我試圖閱讀Stack上的析構函數,但我感到比澄清更困惑。 我假設SegFault來自需要釋放的內存,並且我知道我應該學習如何通過此分配動態分配內存。 構造函數和析構函數對於此過程至關重要,但是有人可以對我盡可能簡單地分解它嗎?


編輯:

我通過實施Fureeish的答案解決了細分錯誤。 我的代碼已在上面更新。

唯一剩下的詢問是對銷毀者及其目的的詢問。 我是否需要為Vector實現一個,否則Container會自動調用它嗎?

您決定自己管理內存,但從未分配任何內存。 您在這里和那里都缺少一些new 例如,給定一個:

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

for()循環遍歷elemelem是未初始化的指針。 您將其視為指向動態分配數組的指針,但是它只是指向一些垃圾值。 記住-首先分配,然后繼續( 當您決定自己管理內存時。通常,您應該更喜歡使用標准實現)。

正確的版本應如下所示:

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

您在使用其他構造函數時從未遇到此問題的事實只是您非常幸運,而且未定義的行為是偷偷摸摸的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM