C++ CopyConstructor 引发的异常!!
代码如下:
void CopyStr(char *&destination, char *&source) { int sz = strlen(source) + 1;//此处引发异常!!
destination = new char[sz];
for (unsigned i = 0; source[i] != '\0'; i++)
destination[i] = source[i];
destination[sz - 1] = '\0';
return;
}
Data::Data(Data &adata) {
CopyStr(adata.P_name, P_name);
CopyStr(adata.address, address);
CopyStr(adata.number, number);
}
代码说明:Data类现在有三个char*成员,分别是P_name,address和number。
编译图片:
求大神解答,谢谢!!
回答:
首先char *&source这种参数改为char *const &source
,其次CopyStr(adata.P_name, P_name),这种改为CopyStr(P_name, adata.P_name)。
这是我测试的代码,直接可以运行:
#include <iostream>#include <cstring>
using std::cout;
using std::endl;
using std::strlen;
class Data
{
public:
char *a = "";
char *b = "";
char *c = "";
Data(char *a, char *b, char *c):a(a),b(b),c(c) {};
Data(Data const &data);
};
int CopyStr(char * &des, char * const &source)
{
int sz = strlen(source) + 1;
des = new char(sz);
for (unsigned i = 0; source[i] != '\0'; i++)
*(des +i) = source[i];
*(des+sz - 1) = '\0';
return 0;
}
Data::Data(Data const &data)
{
CopyStr(a, data.a);
CopyStr(b, data.b);
CopyStr(c, data.c);
}
int main()
{
Data data = Data("abcd", "b", "c");
char * p = "232323";
Data data2 = Data(data);
char * p2 = "1232";
CopyStr(p2, p);
cout << p2 << endl;
cout << data.a << endl;
cout << data2.a << endl;
return 0;
}
回答:
调用CopyStr时的第二个参数(比如P_name)是哪里来的?
回答:
vs会用0xCCCCCCCC填充未初始化的内存区域(这也是烫烫烫
的由来);
考虑到你访问到了0xCCCCCCCC,所以要不就是你传进去了个非法指针,要不就是这个char*
指针对应的字符串没有以'0'结尾;
可以试着输出一下source
的值,然后逐字节输出指针所指向的数据试试
以上是 C++ CopyConstructor 引发的异常!! 的全部内容, 来源链接: utcz.com/p/192464.html