Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator "<<" to a pointer

I have a class Terminallog which is overloading the << operator. If I do the following

Terminallog clog(3);
clog << "stackoverflow.com is cool" << endl;

everything works fine. "stackoverflow.com is cool" is printed in a nice colored way to the screen, exactly what Terminallog is supposed to do.

Now I try

Terminallog* clog = new Terminallog(3);
clog << "stackoverflow.com is cool" << endl;

which gives me a compiler error:

error: invalid operands of types ‘Terminallog*’ and ‘const char [5]’ to binary ‘operator<<’

I can see that it is problem passing the "<<" operator to a pointer, but how can I get the same behaviour as with the non pointer version? I could simply dereference the pointer, but that would create a local copy of the object (which is no good for performance isn't it?)

Therefore I wonder what is the correct way to do it?

Thanks in advance

ftiaronsem

like image 507
ftiaronsem Avatar asked Dec 04 '22 22:12

ftiaronsem


2 Answers

Dereferencing a pointer to write

*clog << "My message" << endl;

does not create a copy of the object being pointed at. In general, pointer dereferences don't make copies, and the only way to make a copy is to either explicitly create one, pass an object into a function by value, or return an object from a function by value. The above code with the pointer dereference is probably what you're looking for.

like image 167
templatetypedef Avatar answered Dec 09 '22 13:12

templatetypedef


Actually dereferencing the pointer gives you a reference, not a copy, so you're fine. (Attempting to copy a stream would and should fail, anyway; streams are not containers but flows of data.)

*clog << "text" << std::endl;

You can't write a free ("global") function operator<< taking a pointer-to-TerminalLog on the left and the other stuff on the right, because the language requires at least one of the operands to operator<< to be a class or enum type, and your RHS argument often won't be one.

like image 26
Lightness Races in Orbit Avatar answered Dec 09 '22 13:12

Lightness Races in Orbit