Suggested modification to TBuffer:ReadString


The following piece of code

void MyClass::my_method(const TBuffer * buf)
  const int STRING_MAX_LENGTH = 1024;
  char str[STRING_MAX_LENGTH];
  buf->ReadString(str, STRING_MAX_LENGTH);
  cout << " message: " << str << endl;

fails for two reasons (using this implementation as a reference):

(1) the integer argument (1024) cannot be constant. A modification of the source code as follows would solve this problem:

int max2 = max;
if (max2 == -1) max2 = kMaxInt;

   while (nr < max2-1) {
// etc...

One may argue that this is less elegant. However, the user should be able to call it with either a const or a non-const integer. The customer is always right. :wink:

(2) ReadString is not const, therefore the compiler assumes that “buf” could be modified. By looking at the code I don’t think that this is the case, and therefore ReadString could be declared const. Am I wrong?



Hi Christos,

my_method() fails for the reason that it has a “const TBuffer*” as argument while TBuffer::ReadString() is not const. So to make it work you would either have to change the argument to “TBuffer*” or cast the const away with const_cast<>. Passing “const int” by value is no problem, the ReadString() will see a value on the stack of 1024 and this stack item can be changed without problem. Also ReadString() cannot be made const since there is a call to TBuffer::operator>>(char*) (*this >> ch) which cannot be made const since it changes state in the TBuffer.

Cheers, Fons.

Hi Fons,

You are right about the const-ness of the integer (this is what happens if you work late at night…). #-o

As far as the 2nd point goes: I naively assumed that the operator>>

TBuffer::operator>>(char*) (*this >> ch) 

was a simple “copy”. I now looked at the code and I see that this is not true.

Apologies for wasting your time with this!