简体   繁体   中英

is there any risk using std::addressof(std::cout) instead of &std::cout?

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);

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.

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.

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 & .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM