c++ - 创建新指针的方法

标签 c++ pointers c++11

我正在尝试使用两种方式创建一个新指针,它们的意思相同吗?

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/

相关文章:

c++ - 基于基类方法的生成类中的运算符重载

c++ - 为什么类型应该放在未命名的命名空间中?

c++ - 与 'operator=' 不匹配(操作数类型为 'std::vector<int>' 和 'int'

c# - 从 DLL 在 C# 中调用 C++ 函数 - 奇怪的参数

c++ - 使用 WriteProcessMemory 和指针写入另一个进程的内存

c - 我如何修复此代码以使用指针检查数字是否是回文?

c++ - 使用通用引用实现前向函数

c++ - Vulkan 中多个具有透明度的绘制调用之间是否需要同步?

c++ - 如何删除在函数中创建的指针并作为返回值

c++ - 寻找滥用枚举的替代方法