c++ - 作者在解释 C++ 中的堆栈和堆时是否犯了错误,或者我误读了什么?

标签 c++ c++11

代码如下:

int main()
{
    using namespace std; 
    int nights = 1001; 
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl; 
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}

下面是作者对代码的注释:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.


最初的问题:

现在我担心的是:变量 pd 是由关键字 new 创建的,所以它应该存储在名为 heap 的区域中就像变量 pt 一样,因为它们都是由关键字 new 创建的。

我在这里遗漏了什么吗?非常感谢您的意见。

基于保留的修订问题/跟进:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value stored in the stack, but again how is that possible if the variable was create during "runtime" with the keyword new, so it should be in the heap, not the stack.

请尝试使用上面的代码作为引用,尤其是您的答案中的**变量(nights、pd 和 pt),以便我可以从该代码的角度理解它。

最佳答案

指针变量ptpd 存储在堆栈中。他们指向的值,用新分配的,存储在堆上。

如果我写了一个标有“湖”的箭头的标志,这并不意味着标志本身就是一个湖,也不意味着它必须安装在湖中。相反,它应该安装在坚实的地面上,指向湖的方向。

关于c++ - 作者在解释 C++ 中的堆栈和堆时是否犯了错误,或者我误读了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429933/

相关文章:

c++ - copy-and-swap 习语在 C++11 中仍然有用吗

c++ - 将虚拟复制构造函数添加到 std::packaged_task

c++ - 如何在qt中同时移动滚动条

c++ - C++检查unordered_map/map的std::array包含相同的元素类型

c++ - 实现字符串(城市)图的最简单方法是什么?

c++ - 修改元组 vector 中的元组 C++

c++ - 为什么 std::lock 不支持超时?

c++ - 初始化程序引用列表的替代方法

c++ - 本地 std::bernoulli_distribution 如何创建准确分布的数据?

c++ - 如何在进行 GoogleTest 时跳过源代码中的部分“代码”