3

I am implementing reference counting in this program..

class plain_class{
public: int ref_count;
    char *data;
    plain_class(const char *);      
    ~plain_class();
};
class ref_count{
private:
    plain_class *p;
public:
    ref_count(const char *);
    ref_count(const ref_count &);
    ref_count& operator=(const ref_count &);
    void show_context();
    ~ref_count();
};
ref_count::ref_count(const char *str)
{
p=new plain_class(str);
}
ref_count::ref_count(const ref_count &ref)
{
p=ref.p;
p->ref_count++;
cout<<"reference count value="<<p->ref_count<<endl;
}
ref_count& ref_count::operator=(const ref_count &r1)   //= operator overloaded function
{
if(*(this)==r1){
    cout<<"Initializing to itself"<<endl;
    return *this;
}
p=r1.p;
p->ref_count++;
cout<<"reference count value="<<p->ref_count<<endl;
return *this;
}

int main(int argc, char *argv[])
{
ref_count r1("Hello_world");
r1.show_context();
ref_count r2=r1;
r2=r2;           //Error signature not matching to call = operator overload function
return 0;
}

Have not written some functions purposefully.

While compiling I am getting this error

 In member function ‘ref_count& ref_count::operator=(const ref_count&)’:
 no match for ‘operator==’ in ‘*(ref_count*)this == r1’

I always used to write like this in my previous program but this is not compiling..

3 Answers3

1

Just use

 if(p==r1.p)---> for just pointer check
 or if(this==&r1)---> for object check
 instead of if(*(this)==r1){}

It will work..

Santosh Sahu
  • 2,134
  • 6
  • 27
  • 51
  • This doesn't check for self-assignment. If you add new members, you'll have to check those too. – Luchian Grigore Nov 14 '13 at 14:45
  • @LuchianGrigore you are correct it i just made for member variables but now after again compilling i found out this is also working.. – Santosh Sahu Nov 14 '13 at 14:48
  • Self assignment isn't possible with objects of different types. – Wolf Nov 14 '13 at 14:50
  • @WolfP. ref_count r1("Hello_world"); ref_count r2=r1; r2=r2; .........Here r1 and r2 are objects of ref_count class?? – Santosh Sahu Nov 14 '13 at 14:56
  • @SantoshSahu The code `(this !=&rhs)` protects against self assignment. Self assignment is only possible, if you try (in most cases accidentally) to assign one object to itself, like in your example `r2=r2`. **One object** has always the same type. The protection mechanism ensures that you don't write and read on the same address at the same time. – Wolf Nov 14 '13 at 15:18
1

Like this

if(this==&r1){

But copy and swap is a better way

Community
  • 1
  • 1
john
  • 85,011
  • 4
  • 57
  • 81
0

Instead of

if(*(this)==r1)

you probably want

if(this==&r1)
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625