簡體   English   中英

在C ++中實現矢量時發生運行時錯誤

[英]Runtime error while implementing vector in c++

我正在嘗試在C ++中實現我自己的vector版本。 到目前為止,我已經做到了。

#include<iostream>
#include<string>

using namespace std;


template<class T>
class vec
{
public:
    T *a;
    int i,N;
    vec(int N=0):N(N)
    {
        i=-1;
        a=(T *)malloc(N*sizeof(T));
    }
    void push_back(const T& t);
    T at(const int& index) const;
};

template<class T>
void vec<T>::push_back(const T& t)
{
    if(++i==N)
    {
        a=(T *)realloc(a,(++N)*sizeof(T));
    }
    a[i]=t;
}

template<class T>
T vec<T>::at(const int& index) const
{
    return a[index];
}

int main()
{
    vec<string> v;
    v.push_back("2");
    v.push_back("1");
    v.push_back("3");
    cout<<v.at(0)<<endl;
    return 0;
}

但是運行此程序時出現運行時錯誤上面的代碼中的錯誤在哪里? 我正在使用C ++和Visual Studio來運行。

在這種情況下,您需要使用新的展示位置。

像這樣的東西:

// Allocate memory
void* mem = malloc(sizeof(std::string));

// Call constructor via placement new on already allocated memory
std::string* ptr = new (mem) std::string();

但是隨后,您被迫為此內存顯式調用析構函數

ptr->~std::string();

總體而言-這並不是實現所需目標的好方法。 使用常規的new \\ delete運算符並在重新分配時復制內部數據(在STL向量中如何完成)更方便。

暫無
暫無

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

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