Solving aliasing problem in c++
I was trying following code in which I defined copy c'tor explicitly to solve aliasing problem.
But code is giving runtime error.#i开发者_JS百科nclude<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. But in destructor of the class you are doing delete[] str;
, since the memory for the str
is not allocated using new[]
it is crashing. 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
.
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.
精彩评论