简体   繁体   中英

Runtime error while implementing vector in c++

I am trying to implement my own version of vector in c++. 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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