解决c ++中的别名问题

时间:2010-07-23 11:22:46

标签: c++ constructor copy

我正在尝试使用明确定义copy 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;
}

1 个答案:

答案 0 :(得分:8)

问题出在这个构造函数中:

 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提到的self assignment

相关问题