解决c ++中的别名问题

Hap*_*tal 0 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;
}
Run Code Online (Sandbox Code Playgroud)

Nav*_*een 8

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

 word(const char *s) // No default c'tor
    {
      str=const_cast<char*>(s); 
      cnt=strlen(s);
    }
Run Code Online (Sandbox Code Playgroud)

在这里,您没有分配任何内存来将字符串复制到str变量中.但是在你正在做的类的析构函数中delete[] str;,因为str未使用new[]它分配的内存正在崩溃.您需要分配与复制构造函数中的内存类似的内存,并将字符串复制到新分配的内存中.或者更好的是,使用std::string.

编辑:如果你真的不想std::string出于某种原因使用,你还需要一个赋值操作符,检查@icabod提到的自我赋值.

  • @Happy Mittal:您没有在此代码中使用它,但这并不意味着您明天不会使用它.当你编写一个类并且你正在编写一个复制构造函数时,你*应该*编写一个赋值运算符. (2认同)