简体   繁体   English

在C ++中实现矢量时发生运行时错误

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

I am trying to implement my own version of vector in c++. 我正在尝试在C ++中实现我自己的vector版本。 So far I have done this.. 到目前为止,我已经做到了。

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

But I am getting a run time error when I run this Where is the error in the above code? 但是运行此程序时出现运行时错误上面的代码中的错误在哪里? I am using c++ and visual studio to run. 我正在使用C ++和Visual Studio来运行。

In this case you need to use placement new. 在这种情况下,您需要使用新的展示位置。

something like this: 像这样的东西:

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

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

But then, you are forced to explicitly call destructor for this memory 但是随后,您被迫为此内存显式调用析构函数

ptr->~std::string();

Overall - this is not really good way to achieve what you want. 总体而言-这并不是实现所需目标的好方法。 It's more convenient to use usual new\\delete operators and copy internal data on re-allocation (how it was done in STL vector) 使用常规的new \\ delete运算符并在重新分配时复制内部数据(在STL向量中如何完成)更方便。

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

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