断点指令执行

问题描述 投票:0回答:1

我正在开发一个二进制类,它使用三态布尔值来创建可测量(按大小)的布尔字符串数组,可以将其转换为莫尔斯电码(TRUE = 破折号,FALSE = 点)。我正在使用 Arduino IDE(这意味着我不能对 std 命名空间使用任何东西)和带有 LED 的电路来测试莫尔斯电码,但我偶尔会使用 Visual Studio 2022 来帮助调试问题。当我声明一个二进制对象变量,然后在构造函数中赋值,然后使用重载的赋值运算符时,问题就开始出现了。 Microsoft Visual Studio 给我的详细信息是:

“在 ConsoleApplication1.exe 中执行了断点指令(__debugbreak() 语句或类似的调用)。”

我将错误详细信息复制到搜索栏中,并阅读了有关此问题的其他论坛帖子(包括来自此处的 Stack Overflow)。我发现问题在于赋值运算符重载函数中的

delete[] triboolList

void Binary::operator=(tribool newElement) { //For reference, triboolList is of tribool Type
    //The tribool type is defined as: enum tribool{DELIM=-1, FALSE, TRUE};
    delete[] triboolList; //This is the problematic line
    if (newElement == DELIM) {
        triboolList = new tribool(DELIM);
    }
    else {
        triboolList = new tribool[2];
        triboolList[0] = newElement;
        triboolList[1] = DELIM;
    }
}

当我注释掉有问题的行时,代码再次开始工作。这是我的主要功能,以防有人好奇:

Binary code;

tribool test[5] = { FALSE,TRUE,FALSE,FALSE,DELIM };
code = Binary(test); //Parameter Construction
std::cout << code << std::endl;
//morse(code); //Functions used in the Arduino IDE that I couldn't port over to Visual Studio
//morse(code);
code = TRUE; //This line causes the Breakpoint Instruction Executed error
code += TRUE; 
code += TRUE;
//morse(code, 1); //Arduino IDE custom function that can't be tested on Visual Studio
std::cout << code << std::endl;

我知道摆脱有问题的行可以解决我的问题,但我担心它也会浪费内存地址。我的担忧是否重大,或者我只是反应过度? (如果有人好奇,我的类确实有一个析构函数,只是

delete[] triboolList;

在听说 3 规则后,我还将分享我的复制构造函数和复制赋值运算符:

Binary::Binary(const Binary& copyBinary) { //Copy Constructor
    triboolList = new tribool[triLength(copyBinary.triboolList) + 1]; 
    for (int i = 0; i < (int) triLength(copyBinary.triboolList); i++) { 
        triboolList[i] = (const tribool)copyBinary.triboolList[i]; 
    } 
    triboolList[triLength(copyBinary.triboolList)] = DELIM; 
}

Binary& Binary::operator=(const Binary& copyBinary) { //Copy Assignment Operator
    delete[] triboolList;
    triboolList = copyBinary.triboolList;
    return *this;
}
c++ arduino-ide
1个回答
0
投票

你的赋值运算符不会检查自赋值,加上会出现双重释放错误,因为你只是在对象之间复制指针值。

也可以使用复制/交换习惯用法来代替此方法。

既然你说Arduino没有

std::swap
,它应该可以使用以下内容轻松实现:

Binary& Binary::operator=(Binary copyBinary) 
{ 
   tribool* temp = triboolList;
   triboolList = copyBinary.triboolList;
   copyBinary.triboolList = temp;
   return *this;
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.