当我使用需要计算数组单元格地址的模板时,奇怪的C++行为
Strange C ++ behavior when i using a template in which need to calculate the address of an array cell
我创建了一个矩阵类,例如一个简单的清理函数
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->lenght
和this->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;
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- arr[-1]在c++中的奇怪行为
- 继承期间显示未知行为的子类
- 如何在c++中使用引用实现类似python的行为
- G锁定铸造到基础上会释放模拟行为
- 在C++中对T*类型执行std::move的意外行为
- std::当在256字节边界上写入整数时,流的奇怪行为
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 奇怪的构造函数行为
- 重载运算符new[]的行为取决于析构函数
- 不同语言中相同代码的不同行为
- 处理除以零会导致<csignal>意外行为
- 试图理解类对象的行为
- c++11评估顺序(未定义的行为)
- 从结构寻址时,MMAP变量的行为很奇怪
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 读取文件时运行时的未知行为
- strncpy之后的char数组的错误行为
- 此增量后语句是否会导致未定义的行为?