2

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
Jomasi
  • 323
  • 1
  • 4
  • 14
  • As you say, `delete this` as such is not a problem. But after deleting the object, there is nothing left. You can't do **anything** with it - it just isn't there anymore! – Bo Persson Mar 20 '11 at 10:23

3 Answers3

2

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.
Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • 1
    "Also `delete this` results an undefined behavior." -- nothing of the sort: http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.15 – Jon Mar 20 '11 at 02:48
  • @Jon - That always confuses me. What if there are statements that needed to executed by `this` after deleting it ? Does that behavior defined ? – Mahesh Mar 20 '11 at 02:50
  • The link I gave clearly states that doing such *is* undefined behavior. But the actual `delete this` is not undefined behavior under specific circumstances. There are (a few, corner) cases where you really do want to `delete this`, and it will work fine. – Jon Mar 20 '11 at 02:54
  • Contrary to common belief, `this` is *not* `const` (it's an rvalue, however). – fredoverflow Mar 20 '11 at 08:02
2

You can't assign to this. Consider creating a static method that creates and returns the new instance.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0

I think the error message is telling you what you need to know. The this keyword isn't an lvalue, and therefore you can't assign to it. Why can't you just do this?:

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

Or, if it's really a hash table, create an "empty" method that walks the elements and deletes them all rather than deleting itself.

easel
  • 3,982
  • 26
  • 28