Reputation: 39
I am using std::cout
for logging and sonarqube reports error when "Don't take the address of 'cout', call it from a lambda instead".
std::ostream *streamp;
streamp = &std::cout;
When I use the below code there is no error observed in sonarqube. Is using std::addressof
on std::cout
function safe?
std::ostream *streamp;
streamp = std::addressof(std::cout);
Upvotes: 1
Views: 162
Reputation: 45684
std::cout
is an object, not a function, thus the rules forbidding taking the address of most standard functions don't apply.
std::addressof()
is only needed where the address-operator might be overloaded (generally a bad thing to even consider), and thus is used in templates to avoid surprises. It is not needed for any standard types, and thus neither objects.
In conclusion, get the tool fixed or ignore that warning, your choice, but don't bend your code into a pretzel.
To expand on standard functions, most functions in the standard library aren't designated "addressable".
Thus, taking their address might result in surprises, all the way from "working" by happenstance, over giving a function-pointer with an unexpected signature (more arguments, unexpected calling-convention, whatever), to failing to compile at all. And that might change with any change to the toolchain.
Upvotes: 2
Reputation: 16690
The difference between &x
and std::addressof(x)
(for variables of class type) only occurs if x
has an overloaded &
operator.
addressof
is for "no, no, I really want the address of this thing, no matter what the class designer has decreed".
That being said, 99++% of the time &x
is fine. It's certainly fine for cout
, since you can look and see that it doesn't have an operator &
.
Upvotes: 0
Reputation: 474136
Yes, using addressof
on std::cout
is safe. But since using &
on std::cout
is equally safe, the only reason to do it is to quiet a tool that clearly is giving you a false-positive (that it, it doesn't realize what addressof
is doing).
It would be better to use &
and employ whatever mechanisms exist in the tool to turn off false-positives.
Upvotes: 3