gpt4 book ai didi

C++ 调试断言失败 _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

转载 作者:行者123 更新时间:2023-11-30 19:46:10 24 4
gpt4 key购买 nike

我在这里查看了类似的问题,但仍然无法意识到我做错了什么。请帮忙。

我需要为大小有限的字符串类制作模板(就像在 Pascal 中一样)代码如下:http://pastebin.com/syZf3yM8

错误如下:http://i.stack.imgur.com/4Jo8i.png

最佳答案

在 my_string 析构函数中,您的代码是:

~my_string () {
delete [] this->text;
}

你不应该这样做,因为文本是数组,而不是指针。当您调用*S3 = *S1 + *S2时,my_string <max_size, T> operator+(const my_string& s)叫做。在此运算符中,my_string <max_size, T> res是局部变量并且在堆栈中。当该功能结束后,该资源将被自动删除。所以将 res 分配给 S3 是错误的。你可以这样修复:

~my_string () {

}

my_string <max_size, T> operator+(const my_string& s) {
my_string <max_size, T> res;
int count = 0;
while (this->get_char(count) != '\0') {
res.set_char(this->get_char(count), count);
count++;
}

for(int i = 0; count < max_size; i++){
if (s.get_char(i) == '\0') { res.set_char('\0', count); break; }
res.set_char(s.get_char(i), count);
count++;
}
return res;
}



my_string& operator=(const my_string& s){
int size=s.get_length();
for (int i = 0; i < size; i++){
this->set_char(s.get_char(i),i);
}
return *this;
}

最后在主函数中:

delete S1;
delete S2;
delete S3;

关于C++ 调试断言失败 _BLOCK_TYPE_IS_VALID(pHead->nBlockUse),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24381500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com