[英]Solving aliasing problem in c++
我正在嘗試遵循以下代碼,在其中明確定義了復制c'tor來解決別名問題。
但是代碼給運行時錯誤。
#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;
}
問題出在這個構造函數中:
word(const char *s) // No default c'tor
{
str=const_cast<char*>(s);
cnt=strlen(s);
}
在這里,您沒有分配任何內存來將字符串復制到str
變量中。 但是在類的析構函數中,您正在執行delete[] str;
,因為str
的內存未使用new[]
分配,所以它崩潰了。 您需要分配與復制構造函數中類似的內存,然后將字符串復制到新分配的內存中。 還是更好,使用std::string
。
編輯:如果您真的出於某種原因不想使用std::string
,您還需要一個賦值運算符,並檢查@icabod提到的自我賦值 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.