解决C++中的混叠问题

解决C++中的混叠问题,c++,constructor,copy,C++,Constructor,Copy,我在尝试下面的代码,其中我显式地定义了copyc'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

我在尝试下面的代码,其中我显式地定义了copyc'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,还需要一个带有check for的赋值运算符,如@icabod所述

Naveen已经向您显示了一个错误。另一个原因是您的类缺少赋值运算符。谷歌的规则三。你为什么要这么做?为什么不使用std::string?@glowcoder:这不是家庭作业。我在C++中阅读思考,其中给出了一个复杂的例子。我只是想通过制作一个小程序来理解这个概念。同样值得一提的是,这里没有赋值运算符,所以在方法foo中,您实际上会尝试删除由名词指向的数据。如果在类中使用指针,您确实也需要一个运算符。@icabod。。为什么我需要operator=因为在foo中,我正在创建一个新对象,而不是分配给任何以前构造的对象。@Happy Mittal:您在这段代码中没有使用它,但这并不意味着您明天就不会使用它。当您编写一个类并向其编写一个副本构造函数时,您还应该编写一个赋值运算符。这在几个方面都要好得多。