gpt4 book ai didi

c++ - 如何解决错误(projectname 已触发断点)?

转载 作者:行者123 更新时间:2023-11-27 23:36:47 26 4
gpt4 key购买 nike

在我运行该程序后,我收到一条错误消息,指出 projectname 已触发断点。我仍然不知道错误是什么。我认为缺少一个成员函数,但有人可以帮助我吗?

#include "AClass.h"
#include <iostream>

using namespace std;

int main()
{
AClass* x = new AClass(10, -1.0);
AClass y = *x;
delete x;
return 0;
}

我的cpp文件中的代码如下:

#include "AClass.h"
#include <iostream>
using namespace std;

// Constructor
AClass::AClass(int len, double val)
: length(len)
{
if (len < 0) {
cout << "Invalid data length = " << len << endl;
data = NULL;
}

else {
data = new double[length];
for (int i = 0; i < length; i++)
data[i] = val;
}
}

// Destructor
AClass::~AClass()
{
// delete data if it is not NULL
if (data) delete[] data;
}

最佳答案

您的 AClass 成员 double* data; 将被复制到这里:

AClass y = *x;

由于您没有提供复制/移动构造函数/赋值运算符,在这些情况下,原始指针将被原样复制,delete[] data 将被由析构函数中的 xy 完成。

处理原始指针时强制读取: https://en.cppreference.com/w/cpp/language/rule_of_three

还有这些:
What is The Rule of Three?
Rule-of-Three becomes Rule-of-Five with C++11?

下面是上述文章中提到的成员函数的示例实现。它有点多 - 并且容易出错,这就是为什么使用标准容器几乎总是更好。

#include <algorithm>
#include <iostream>
#include <utility>

class AClass {
public:
AClass(size_t len, double val);

// rule of five:
AClass(const AClass& rhs); // copy constructor
AClass(AClass&& rhs); // move constructor
AClass& operator=(const AClass& rhs); // copy assignment
AClass& operator=(AClass&& rhs); // move assignment
~AClass();

private:
size_t length; // use an unsigned type since you only accept unsigned values
double* data;
};

// destructor
AClass::~AClass() {
delete[] data;
}

AClass::AClass(size_t len, double val) :
length(len),
data(new double[length])
{
std::fill_n(data, length, val);
}

// copy constructor
AClass::AClass(const AClass& rhs) :
length(rhs.length),
data(new double[length])
{
std::copy_n(rhs.data, length, data);
}

// move constructor
AClass::AClass(AClass&& rhs) :
length(std::exchange(rhs.length, 0)),
data(std::exchange(rhs.data, nullptr))
{}

// copy assignment
AClass& AClass::operator=(const AClass& rhs) {
double* tmpdata = new double[rhs.length];
delete[] data;
length = rhs.length;
data = tmpdata;
std::copy_n(rhs.data, length, data);
return *this;
}

// move assignment
AClass& AClass::operator=(AClass&& rhs) {
// leave the destruction up to the moved-from object
std::swap(length, rhs.length);
std::swap(data, rhs.data);
return *this;
}

int main() {
AClass* x = new AClass(10, -1.0);
AClass y = *x;
delete x;
}

关于c++ - 如何解决错误(projectname 已触发断点)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58632103/

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