简体   繁体   中英

C++ vector implementation error

I have made a basic vector class in C++, which is not finished, but is a start. I was testing out the operator= function, when I found a problem - [most of] the values passed were wrong.

Desired Output:

12345678910

12345678910

Actual Output:

12345678910

12-842203133-842150451-842150451-842150451-842150451-842150451-842150451-8421504 51

template < typename _Ty > class vector
{
public:
    typedef _Ty *iterator;
    typedef vector<_Ty> _Myt;
    vector() : __size(0), __data((_Ty *)calloc(1, sizeof(_Ty))){}
    vector(_Myt &_Rhs)
    {
        __data = (_Ty *)malloc((__size = _Rhs.size()) * sizeof(_Ty));
        memcpy(__data, _Rhs.__data, _Rhs.size());
    }
    ~vector(){ free(__data); }
    _Myt &push_back(const _Ty &_Rhs)
    {
        __data = (_Ty *)realloc(__data, ++__size * sizeof(_Ty));
        __data[__size - 1] = _Rhs;
        return *this;
    }
    size_t size() const
    {
        return __size;
    }
    iterator begin() const
    {
        return &__data[0];
    }
    iterator end() const
    {
        return &__data[__size];
    }
    _Myt &operator=(_Myt &_Rhs)
    {
        __data = (_Ty *)realloc(__data, (__size = _Rhs.size()) * sizeof(_Ty));
        memcpy(__data, _Rhs.__data, _Rhs.size());
        return *this;
    }
private:
    _Ty *__data;
    size_t __size;
};

int main()
{
    vector<int> v, v1;
    for (int i = 1; i <= 10; ++i)
    {
        v1.push_back(i);
    }
    for (vector<int>::iterator i = v1.begin(); i != v1.end(); ++i)
    {
        std::cout << *i;
    }
    std::cout << "\n";
    v = v1;
    for (vector<int>::iterator i = v.begin(); i != v.end(); ++i)
    {
        std::cout << *i;
    }
    getchar();
}

What is wrong with my code?

memcpy(__data, _Rhs.__data, _Rhs.size());

您的分配运算符中

memcpy(__data, _Rhs.__data, _Rhs.size() * sizeof(_Ty));

There is another thing wrong with your implementation. And that is the push_back operation.

The first issue is performance. You might copy the whole array on every insertion making it O(n) which is not what you should have. You might fix this by for example doubling the size of the container when it is full.

The second error is that you shouldn't ever copy class objects with realloc, memcpy and similar functions since it leads to undefined behavior. In the case of realloc what if the object contained a pointer to some part of itself? You would break it.

To fix this you might look into this

void* operator new(std::size_t size, void* ptr) noexcept;

variant of the new operator called placement new . You might use it to implement the vector correctly.

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