简体   繁体   English

为什么重新分配先前分配为 nullptr 的指针无效?

[英]Why is it invalid to reassign a pointer that was previously assigned nullptr?

I am new to C++ and am following the book "Programming Principles and Practices using C++".我是 C++ 新手,并且正在关注“使用 C++ 的编程原则和实践”一书。 I came across something that I could not understand completely.我遇到了一些我无法完全理解的东西。 Hopefully someone can help me understand this.希望有人可以帮助我理解这一点。

Why is this invalid?为什么这是无效的?

int* p = nullptr;
*p = 7;

nullptr is a special address. nullptr是一个特殊的地址。 In particular, nothing can ever be stored there.特别是,任何东西都不能存储在那里。 Attempting to dereference a null pointer is undefined behavior (in fact, it's the first example on that list).尝试取消引用空指针是未定义的行为(事实上,这是该列表中的第一个示例)。

Now, to be clear, what you're doing is not reassigning a pointer itself.现在,要清楚的是,您所做的不是重新分配指针本身。 Given this code:鉴于此代码:

int* p = nullptr;
*p = 7;

This is dereferencing the pointer and then reassigning the value of the thing that the pointer is pointing at.这是取消引用指针,然后重新分配指针指向的事物的 And since nullptr does not point at anything, dereferencing a nullptr is undefined behavior, so the assignment is invalid.而且由于nullptr不指向任何东西,取消引用nullptr是未定义的行为,因此分配无效。

Now, given this code:现在,给定这段代码:

int q = 42;
int* p = nullptr;
p = &q;

This is reassigning the pointer itself.是重新分配指针本身。 This is perfectly valid.这是完全有效的。 We started with a pointer that is pointing to nothing, and then tell it to point to something else (in this case, a local variable).我们从一个不指向任何东西的指针开始,然后告诉它指向其他东西(在这种情况下,是一个局部变量)。 Notice that I don't put a * when I assign to p in this example.请注意,在此示例中,当我分配给p时,我没有放* I never dereference a nullptr , so I never hit that particular problem.我从来没有取消引用nullptr ,所以我从来没有遇到过那个特定的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM