我正在尝试使用两种方式创建一个新指针,它们的意思相同吗?
int* ptn;
int* ptn(nullptr);
最佳答案
I am trying to create a new pointer by using two ways, do they mean the same?
不,他们不会 - 或者至少,不总是。
如果这些变量是在 block 范围内声明的,第一个只会给你一个未初始化的指针,而第二个会将指针初始化为空指针值。所以在第一种情况下:
int main()
{
int* ptn; // This gives you an uninitialized pointer...
if (ptn == nullptr) // ...so this is UNDEFINED BEHAVIOR!
{
// ...
}
}
如果您在将 ptn
初始化为某个值之前无论如何要使用它的值,您将遇到未定义的行为。
另一方面,如果它们在命名空间范围内,这两个声明将是等效的,因为 ptr
将具有静态存储持续时间,并且将被零初始化无论如何:
int* ptn; // This pointer has static storage duration, will be zero-initialized...
int main()
{
if (ptn == nullptr) // ...so no undefined behavior here!
{
// This will be entered...
}
}
根据 C++11 标准的第 8.5/10 段:
[ Note: Every object of static storage duration is zero-initialized at program startup before any other initialization takes place. In some cases, additional initialization is done later. —end note ]
关于c++ - 创建新指针的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16656117/