c++ - 使用复制构造函数 C++ 时出现分段错误
问题描述
一切似乎都很好,但是当我打电话时array2.print()
,它显示分段错误。我究竟做错了什么?
#include <iostream>
#include <initializer_list>
template <typename T>
class DynamicArray
{
private:
const int GROWTH_FACTOR = 2;
const int INITIAL_CAPACITY = 5;
T *m_array;
int m_capacity; // Capacity of the array
int m_size; // Number of added elements
public:
DynamicArray(std::initializer_list<T> elements)
: m_size(elements.size())
, m_capacity(elements.size() * 2)
{
m_array = new T[m_capacity];
std::copy(elements.begin(), elements.end(), m_array);
}
DynamicArray()
: m_size(0)
, m_capacity(INITIAL_CAPACITY)
{
m_array = new T[m_capacity];
}
~DynamicArray()
{
delete[] m_array;
}
DynamicArray(const DynamicArray& other)
: GROWTH_FACTOR(other.GROWTH_FACTOR)
, INITIAL_CAPACITY(other.INITIAL_CAPACITY)
, m_capacity(other.m_capacity)
, m_size(other.m_size)
{
T *m_array = new T[m_capacity];
std::copy(other.m_array, other.m_array + m_size, m_array);
}
int size()
{
return m_size;
}
int capacity()
{
return m_capacity;
}
void resize()
{
int new_capacity = m_capacity * GROWTH_FACTOR;
m_capacity = new_capacity;
T *temp = new T[new_capacity];
std::copy(m_array, m_array + m_capacity, temp);
delete[] m_array;
m_array = temp;
}
void deleteAt(int pos)
{
for (int i = pos; i < m_size - 1; i++)
{
(*this)[i] = (*this)[i + 1];
}
m_size--;
}
void insertAt(T value, int pos)
{
if (m_capacity == m_size)
{
resize();
}
for (int i = m_size - 1; i >= pos; i--)
{
(*this)[i + 1] = (*this)[i];
}
m_size++;
(*this)[pos] = value;
}
void append(T value)
{
insertAt(value, m_size);
}
void print() {
for (int i = 0; i < m_size; i++)
{
std::cout << (*this)[i] << ", ";
}
std::cout << std::endl;
}
T& operator[](int index)
{
if (index < 0 || index > m_size - 1)
{
throw std::invalid_argument("Index out of range!");
}
return m_array[index];
}
};
int main()
{
DynamicArray<int> array = { 1, 2, 3, 4 };
DynamicArray<int> array2 = array;
array2.print();
return 0;
}
解决方案
错误在这里
T *m_array = new T[m_capacity];
它应该是
m_array = new T[m_capacity];
通过声明一个名为的新变量,m_array
您隐藏了要分配的类成员变量。它的技术名称是shadowing,一个好的编译器会警告你。
推荐阅读
- json - 无法将数组传递给 json 字符串
- arrays - 获取单个核心数据元素并组合成单个数组
- firefox - 在 Firefox 的固定选项卡上运行 javascript
- c++ - 我可以从变量中获取对类对象的引用吗
- arrays - 将 Outlook 邮件转换为 Byte[]
- .net-core - DotNet Core 中的条件逻辑 OR 运算符
- powershell - 如何从 MyModule.psm1 中检索 MyModule.psd1 哈希值的值,例如 RootModule、ModuleVersion 和 HelpInfoURI?
- python - 为什么这种获取http客户端的方式会失败?
- java - 带有 jacoco 插件的 SonarQube 覆盖率显示百分比为零,但可以看到单元测试的数量
- angular - 如何从一个ts文件中获取变量到角度的所有其他ts文件中