求帮忙看下哪里出现了问题??
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
#include <memory>
#include <cstdlib>
#include <cstring>
//默认容量
const int default_capacity = 20;
template <class T>
class Vector
{
public:
Vector() : m_capacity_(default_capacity), m_size_(0), m_ptr_(nullptr)
{
}
Vector(int size, T data) : m_size_(size)
{
this->m_capacity_ = default_capacity + size;
this->m_ptr_ = new T[this->m_capacity_];
for (int i = 0; i < this->m_size_; ++i)
{
this->m_ptr_[i] = data;
}
}
Vector(const Vector& v)
{
this->m_ptr_ = new T[v.m_size_];
this->m_size_ = v.m_size_;
this->m_capacity_ = default_capacity + v.m_capacity_;
for (int i = 0; i < this->m_size_; ++i)
{
this->m_ptr_[i] = v.m_ptr_[i];
}
}
~Vector()
{
if (this->m_ptr_ != nullptr)
{
delete[] m_ptr_;
}
std::cout << "destory" << std::endl;
}
int size()
{
return this->m_size_;
}
T& operator[](int index)
{
return this->m_ptr_[index];
}
Vector& operator= (const Vector<T>& v)
{
if (this->m_ptr_ != nullptr)
{
delete[] this->m_ptr_;
this->m_ptr_ = nullptr;
this->m_capacity_ = 0;
this->m_size_ = 0;
}
this->m_capacity_ = v.m_capacity_;
this->m_size_ = v.m_size_;
this->m_ptr_ = new T[this->m_capacity_];
memcpy(this->m_ptr_, v.m_ptr_, this->m_size_ * sizeof(T));
return *this;
}
void push_back(T data)
{
if (this->m_ptr_ == nullptr)
{
this->m_capacity_ = default_capacity;
this->m_size_ = 0;
this->m_ptr_ = new T[this->m_capacity_];
}
// 预留空间大小,当原容量小于要求大小时,才会重新分配
if (this->m_size_ >= this->m_capacity_)
{
T* new_p = new T[this->m_capacity_ * 2];
memcpy(new_p, this->m_ptr_, this->m_size_ * sizeof(T));
this->m_capacity_ *= 2;
delete[]this->m_ptr_;
this->m_ptr_ = new_p;
}
this->m_ptr_[this->m_size_++] = data;
}
void pop_back()
{
if (this->m_size_ >= 1)
{
this->m_size_--;
}
}
private:
int m_size_;
int m_capacity_;
T* m_ptr_;
};
#endif // !VECTOR_H
```c++
#include "vector.h"
#include <iostream>
int main()
{
Vector<int> p1;
Vector<int> p2(3,1);
Vector<int> p3(p1);
Vector<int> p4 = p2;
auto vector = p1;
vector.push_back(1);
//vector.push_back(2);
for (int i = 0; i < vector.size(); i++)
{
std::cout << vector[i] << std::endl;
}
std::cout << p2.size() << std::endl;
std::cout << vector.size() << std::endl;
vector.pop_back();
std::cout << vector.size() << std::endl;
}
```
代码没有问题 就是笔误,应该是这里拷贝构造函数申请内存大小的问题,和push_back时塞数据冲突了。
看下面的图就好,不好意思,很久不接触C++,顺路回顾了一下,过程中可能有错误的理解,你谨慎参考,参考下面
主要就是复制构造函数,以及重载=的逻辑,你实现没问题,笔误导致的问题。
T是对象,不是一段内存,不能memcpy
参考
《C++编程思想》 模板类 缺省构造 赋值构造 拷贝构造
《深度探索C++对象模型》虚表
《C++反汇编与逆向分析技术揭秘》