当我使用需要计算数组单元格地址的模板时,奇怪的C++行为

Strange C ++ behavior when i using a template in which need to calculate the address of an array cell

本文关键字:行为 C++ 地址 单元格 数组 计算      更新时间:2023-10-16

我创建了一个矩阵类,例如一个简单的清理函数

template<typename T>
class matrix
{
public:
matrix(int Lenght, int Height)
{
this->container = new T[this->lenght * this->height];
this->lenght = Lenght;
this->height = Height;
}
void Nulling()
{
size_t A = sizeof(T);
for (int i = 0; i < (this->height * this->lenght); i++)
{
this->container)[i] = 0;
//((T*)this->container)[i] = 0;    // same result
}
}

T* container = nullptr; 
int lenght; 
int height; 
};

当i == 100226时,调试停止并在写入时发生错误(我有512 * 512矩阵,因此其262144元素(

我认为问题是使用模板计算地址不正确,我尝试这种结构

size_t A = sizeof(T);
for (int i = 0; i < (this->height * this->lenght); i++)
{
this->container[0] = 0;
this->container += A;
}

它在 i == 12529 上的原因错误

所以我不知道现在该怎么办。

在你的构造函数中,语句

this->container = new T[this->lenght * this->height];

具有未定义的行为,因为您在为this->lenghtthis->height赋值之前使用它们,因此分配的数组的大小是不确定的。您需要先执行这些作业:

matrix(int Lenght, int Height)
{
this->lenght = Lenght;
this->height = Height;
this->container = new T[this->lenght * this->height];
}

或者,在分配数组时使用输入值而不是类成员:

matrix(int Lenght, int Height)
{
this->container = new T[Lenght * Height];
this->lenght = Lenght;
this->height = Height;
}