#include <type_traits>
int main()
{
int n;
auto* p1 = &n;
auto p2 = &n;
static_assert(std::is_same_v<decltype(p1), decltype(p2)>); // ok
}
auto* p = &n
和 auto p = &n
之间有什么区别吗?或者只是编码风格问题?
最佳答案
Any difference between
auto* p = &n
andauto p = &n
? or just a coding style issue?
在您的示例中,其中 n
是 int
,区别在于编码风格。
但是,如果n
是struct
或class
类型的实例,则提供一元operator&()
,那么就有区别了。如果重载的 operator&
返回任何非指针类型,auto *p = &n
将被诊断为错误。仅当 operator&()
返回 void
时,auto p = &n
才会被诊断为错误。如果后续代码依赖 &n
提供指针,这可能很有用(从某种意义上说,编译器最好尽早诊断问题)。
诚然,重载operator&()
是一种相对罕见(且有风险)的用例,并且重载返回非指针类型的情况相当罕见。然而,给出了现实世界的例子 here和 here .
关于c++ - `auto* p = &n` 和 `auto p = &n` 之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61289179/