Operator "<<" pointer

I have a Terminallog class that overloads the <statement. If I do the following

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

everything is working fine. "stackoverflow.com is awesome" prints beautifully on the screen, exactly what Terminallog should do.

Now i'm trying

 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 see that the problem is passing "<lt;" operator to a pointer, but how can I get the same behavior as with a version without a pointer? I could just dereference the pointer, but that would create a local copy of the object (which is not suitable for performance, right?)

So I wonder how to do it right?

Thank you in advance

ftiaronsem

+4
source share
5 answers

Dereferencing a pointer to a record

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

does not create a copy of the object that it points to. In general, pointer markups do not make copies, and the only way to make a copy is to either explicitly create it, pass an object to a function by value, or return an object from a function by value. The above pointer dereferencing code is probably what you're looking for.

+8
source

In fact, dereferencing a pointer gives you a link, not a copy, so you're fine. (An attempt to copy a stream will and should fail, in any case, the streams are not containers, but data streams.)

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

You cannot write a free ("global") operator<< function using a pointer to TerminalLog on the left and the rest on the right, because the language requires at least one of the operands for operator<< be a class or enumeration type, and your RHS argument will often not be like that.

+4
source

Dereferencing a pointer does not create a copy; it creates a link. You can simply undo it and get the correct behavior, without copying.

+2
source

Simple: (*clog) << "stackoverflow.com is cool" << endl;

This does not create a clog copy.

+1
source
 Terminallog* clog = new Terminallog(3); Terminallog& clog_r = *clog; clog_r << "stackoverflow.com is cool" << endl; 
+1
source

Source: https://habr.com/ru/post/1346008/


All Articles