Consider that we have create a custom type:
1 2 3 4 5 6 |
|
If we want to make it work with qDebug(), we need to implement a streaming operator:
1 |
|
But, wait ...
When we using pure c++, what we do is:
1 |
|
Why QDebug object is passed by value instead of reference?
qDebug() vs. std::cout
In first glance, qDebug() is very similiar to std::cout.
1 2 |
|
However, each time we call qDebug(), a new QDebug
object will be created.
1 |
|
while std::cout is a global std::ostream
object, the header file iostream is more or less like this:
1 2 3 4 5 |
|
Why reference doesn't work for QDebug
We know that,
1 |
|
can be wrriten as:
1 |
|
Which can also be wrriten as:
1 |
|
As we can see, a temporary QDebug object is passed to the function in above statements.
But in C++, we know that,
A temporary cannot be bound to a non-const reference.
That why
1 |
|
should be used instead of
1 |
|
Problem?
Some one complain that, though
1 |
|
doesn't work for qDebug()<<Point(1,2);
, but it indeed works for qDebug()<<""<<Point(1,2);
. Why?
The latter statement can be re-written as
1 |
|
and note that, QDebug has provided the member function for type char *
:
1 |
|
in which a reference to current QDebug object is return.
So C++ compiler will be happy with this now.