C++ - 函数中的局部指针变量有什么类型的存储持续时间,它们存储在哪里?

标签 c++

我正在从 Storage duration 查看 C++ 中的存储持续时间类型.

我只是想知道函数中的局部指针变量具有哪种类型的存储持续时间,因为函数中的非静态局部变量将在 block 结束时被销毁。但这不适用于指针(在本例中是 xPtr)。它们将一直存在到程序结束,尽管我们不能再触及它。

automatic storage duration. The storage for the object is allocated at the beginning of the enclosing code block and deallocated at the end. All local objects have this storage duration, except those declared static, extern or thread_local.

static storage duration. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern. See Non-local variables and Static local variables for details on initialization of objects with this storage duration.

我的另一个问题是,为什么系统分配相同的内存地址 0x00000041C69EF754 仍然由 xPtr 指向临时变量 x 第二次进入函数时。

void localPointer()
{
    int x = 10; 
    static int* xPtr = &x; // 0x00000041C69EF754 - 0a 00 00 00 (data the address contains)
    std::cout << "end of function" << std::endl;
}

int main()
{
    // first enter
    localPointer();

    /* 
        the address 0x00000041C69EF754 and its value still 
        exsit out of the scope of the function localPointer
    */
    std::cout << "-----------------------------------------" << std::endl;

    // second enter
    localPointer();
    return 0;
} 

最佳答案

你的指针也是一个普通的静态变量;使用 new 创建指针时,指针的 是动态的。

在您的示例中,指针一直指向未更改的本地堆栈变量,因为在您进入函数时会重新创建相同的堆栈。

尝试从另一个级别调用此函数,以便 RSP 值发生变化,看看会发生什么。例如,创建另一个函数然后从中调用此函数。

关于C++ - 函数中的局部指针变量有什么类型的存储持续时间,它们存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55585100/

相关文章:

c++ - 如果在 C++14 或更高版本上,不是 const 的成员函数只能是 constexpr

c++ - 如何实现中点位移

c++ - 命名空间 std 中的字符串没有命名类型

c++ - 红皮书毛皮示例不渲染毛皮 (Linux/nvidia gtx675mx)

java - 通过 Java 学习 OpenGL

c++ - OSX 中的 Mongodb connect() 段错误

C++ - 与非平凡类成员类型的 union ?

C++ 11 智能指针的使用

c++ - 使用 Stroustrup 示例的 condition_vairable::wait_for() 问题

c++ - Cryptoauthlib - 匿名 union 只能有非静态数据成员 - 段错误