[英]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::cout
进行日志记录,并且 sonarqube 在“不要获取 'cout' 的地址,而是从 lambda 调用它”时报告错误。
std::ostream *streamp;
streamp = &std::cout;
When I use the below code there is no error observed in sonarqube.当我使用下面的代码时,在 sonarqube 中没有观察到错误。 Is using std::addressof
on std::cout
function safe?在std::cout
function 上使用std::addressof
安全吗?
std::ostream *streamp;
streamp = std::addressof(std::cout);
Yes, using addressof
on std::cout
is safe.是的,在std::cout
上使用addressof
是安全的。 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).但是由于在std::cout
上使用&
同样安全,这样做的唯一原因是让一个明显给你误报的工具安静下来(它没有意识到addressof
正在做什么)。
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::cout
是 object,而不是 function,因此禁止获取大多数标准函数地址的规则不适用。
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. std::addressof()
仅在地址运算符可能过载的情况下才需要(通常甚至考虑到一件坏事),因此在模板中使用以避免意外。 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.因此,获取他们的地址可能会导致意外,从偶然的“工作”,到提供具有意外签名的函数指针(更多 arguments,意外调用约定,等等),到根本无法编译。 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. &x
和std::addressof(x)
之间的区别(对于 class 类型的变量)只有在x
具有重载的&
运算符时才会出现。
addressof
is for "no, no, I really want the address of this thing, no matter what the class designer has decreed". addressof
是“不,不,我真的想要这个东西的地址,不管 class 设计师有什么规定”。
That being said, 99++% of the time &x
is fine.话虽这么说,99++% 的时间&x
都很好。 It's certainly fine for cout
, since you can look and see that it doesn't have an operator &
.对于cout
来说当然没问题,因为您可以查看并看到它没有operator &
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.