[英]Solving aliasing problem in c++
I was trying following code in which I defined copy c'tor explicitly to solve aliasing problem. 我正在尝试遵循以下代码,在其中明确定义了复制c'tor来解决别名问题。
But code is giving runtime error. 但是代码给运行时错误。
#include<iostream>
#include<cstring>
using namespace std;
class word
{
public:
word(const char *s) // No default c'tor
{
str=const_cast<char*>(s);
cnt=strlen(s);
}
word(const word &w)
{
char *temp=new char[strlen(w.str)+1];
strcpy(temp,w.str);
str=temp;
cnt=strlen(str);
}
~word()
{
delete []str;
cout<<"destructor called"<<endl;
}
friend ostream& operator<<(ostream &os,const word &w);
private:
int cnt;
char *str;
};
ostream& operator<<(ostream &os,const word &w)
{
os<<w.str<<" "<<w.cnt;
return os;
}
word noun("happy");
void foo()
{
word verb=noun;
cout<<"inside foo()"<<endl;
cout<<"noun : "<<noun<<endl<<"verb : "<<verb<<endl;
}
int main()
{
cout<<"before foo()"<<endl<<"noun : "<<noun<<endl;
foo();
cout<<"after foo()"<<endl<<"noun : "<<noun<<endl;
return 0;
}
Problem is in this constructor: 问题出在这个构造函数中:
word(const char *s) // No default c'tor
{
str=const_cast<char*>(s);
cnt=strlen(s);
}
Here you are not allocating any memory to copy the string into str
variable. 在这里,您没有分配任何内存来将字符串复制到
str
变量中。 But in destructor of the class you are doing delete[] str;
但是在类的析构函数中,您正在执行
delete[] str;
, since the memory for the str
is not allocated using new[]
it is crashing. ,因为
str
的内存未使用new[]
分配,所以它崩溃了。 You need to allocate memory similar to one you are doing in copy constructor and copy the string into the newly allocated memory. 您需要分配与复制构造函数中类似的内存,然后将字符串复制到新分配的内存中。 Or better still, use
std::string
. 还是更好,使用
std::string
。
EDIT: If you really don't want to use std::string
for some reason, you also need an assignment operator with check for self assignment as mentioned by @icabod. 编辑:如果您真的出于某种原因不想使用
std::string
,您还需要一个赋值运算符,并检查@icabod提到的自我赋值 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.