简体   繁体   中英

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.

#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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM