zfg*_*fgo 0 c++ pointers class dynamic-memory-allocation
我正在学习 C++,但无法理解与指针相关的某些行为。
我有一个简单的自定义对象,如下所示:
class Human {
public:
       //constructor here
private:
       std::string name;
       std::string address;
}
Run Code Online (Sandbox Code Playgroud)
另一个具有指向人类指针的实例变量类型的自定义对象:
class property {
public:
       Human * ppl;//pointer to the above human object
}
Run Code Online (Sandbox Code Playgroud)
并运行这段代码:
Human * human = new Human("Mark", "address");// pointer address 0x123456 for example
Property * property = new Property();
property->ppl = human;//pass the pointer to property's instance variable 
delete human; 
human = NULL;//after deleting and setting it to NULL property.ppl still points to 0x123456
Run Code Online (Sandbox Code Playgroud)
运行上面的代码后,property下的ppl实例变量仍然指向原来的内存地址,但是里面的内容(name和address)都被清除了(现在是空字符串),我想知道为什么会这样?既然我传递了原始指针,为什么删除它并将其设置为NULL后,它仍然指向一个内存地址,但它的内容已被清除?
仅供参考:我使用 XCode 作为调试 IDE 和 C++11
看这个更简单的例子:
int a = 5;
int b = a;
b = 45;
Run Code Online (Sandbox Code Playgroud)
设置的值b并没有改变的价值a。同样,human在代码中设置 的值不会改变 的值property->ppl。
这个概念与delete. 但是,在指针的情况下,您必须非常小心,因为property.ppl不再指向有效内存。您可以访问它,但可能会导致分段错误或其他一些很难调试的错误。