为什么这个 volatile 变量的地址总是为 1?
我想检查变量的地址
volatile int clock;
cout << &clock;
,但它总是说 x 位于地址 1。我做错了什么吗?
I wanted to inspect the address of my variable
volatile int clock;
cout << &clock;
But it always says that x is at address 1. Am i doing something wrong??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
iostreams 会将大多数指针转换为
void *
进行显示 - 但易失性
指针不存在转换。因此,C++ 退回到隐式转换为bool
。如果要打印地址,请显式转换为void*
:iostreams will cast most pointers to
void *
for display - but no conversion exists forvolatile
pointers. As such C++ falls back to the implicit cast tobool
. Cast tovoid*
explicitly if you want to print the address:const void*
有一个operator<<
,但没有volatile void*
的operator<<
,并且隐式转换不会删除volatile
(也不会删除const
)。正如 GMan 所说,所指向类型的简历资格应该与打印地址的业务无关。也许27.7.3.6.2中定义的重载应该是
operator<<(const volatile void* val);
,我无法立即看到任何缺点。但事实并非如此。输出:
There's an
operator<<
forconst void*
, but there's nooperator<<
forvolatile void*
, and the implicit conversion will not removevolatile
(it won't removeconst
either).As GMan says, the cv-qualification of the type pointed to should be irrelevant to the business of printing an address. Perhaps the overload defined in 27.7.3.6.2 should be
operator<<(const volatile void* val);
, I can't immediately see any disadvantage. But it isn't.Output:
这是因为没有重载操作符<<,它接受一个指向
易失性
的指针,并且没有可以满足它的指针转换。根据C++标准,
运算符
<<
对于指向非-静态成员、指向易失性的指针或函数指针,因此尝试输出此类对象会调用到bool
的隐式转换。This is because there is no overload for
operator <<
that takes a pointer tovolatile
, and there is no pointer conversion that could satisfy it.According to C++ standard,
Operator
<<
has no overload for pointers to non-static member, pointers to volatile, or function pointers, so attempting to output such objects invokes implicit conversion tobool
.