将指针内容复制到堆栈变量

时间:2018-09-18 10:59:22

标签: c++11 pointers memory

我想到了这个疑问。这可能吗? 考虑以下代码:

int* p;
int j = 9;
p = &j;
// is it possible to declare int x and store inside 9?
// so if I do delete p; that value is stored in x

预先感谢和问候

1 个答案:

答案 0 :(得分:1)

您绝对可以读取p所引用的值,并将其复制到另一个int中,如下所示:

int x = *p;

// The value has been copied, j and hence *p aren't affected by changes to x:
++x;
assert(x > *p);

但是,您绝对不想delete p,因为它没有与new堆分配。相反,p指向j,而j的生存期由周围的范围自动管理。