Search code examples
c++arrayscopyhashtablethis-pointer

Setting an instance of an object to another one from inside, using this = new Foo()?


I am working with a hash table and to rehash it, I am simply putting all the values into a new hash table, and then setting the executing instance to this new hash table.

I wasn't sure going into it if that was possible, so I just want to confirm if this is the case. I am trying:

Foo *new_foo = new Foo();
...
delete this;
this = new_foo;

I know the problem isn't the delete line, since it doesn't work even without that. This is the error: error: lvalue required as left operand of assignment.

Also, just as a side question, what's the best/standard way for copying allocated arrays? *a = *b? I'm new to C++, obviously, and it would be helpful to know, but not necessary.


Solution

  • Program cannot modify this to point to a different object. this is a constant pointer ( i.e., T* const ).

    this = new_foo; // incorrect.
    

    what's the best/standard way for copying allocated arrays?

    Using *a = *b; doesn't copy the entire array. You are just copying the value at first index of b to first index of a. Use std::copy, instead.


    int a[] = { 1,2,3,4,5 } ;
    int b[5] ;
    
    // To copy element of a to b -
    
    std::copy( a, a+5, b ) ; // you need to include <algorithm> header.