简体   繁体   English

何时在C ++中删除/取消引用

[英]When to delete/dereference in C++

myObj* var = new myObj;
var = other1;

don't need it anymore 不再需要它了

delete var;
var = new myObj;
var = other2;

why can't just dereference instead of deleting and allocating again? 为什么不能只取消引用而不是再次删除和分配?

var->other2;

Dereference does not mean delete: http://en.wikipedia.org/wiki/Dereference 取消引用并不意味着删除: http//en.wikipedia.org/wiki/Dereference

I suggest you go through some tutorials on C++, as you seem to have a misunderstanding of what a lot of the vocabulary actually means. 我建议你阅读一些关于C ++的教程,因为你似乎对很多词汇实际意味着什么有误解。

Remember to use google. 请记得使用谷歌。

Your question is silly, absolutely no offence intended. 你的问题很愚蠢,绝对没有违法行为。 In other words, you have an underlying confusion here, that cannot be addressed by a simple answer to an inquiry. 换句话说,你在这里有一个潜在的混淆,无法通过一个简单的答案来解决。

I'd strongly recommend you read introductory material to C or C++. 我强烈建议您阅读C或C ++的介绍性材料。 The web is full to the brim with excellent lectures, and free e-books. 网络充满了边缘,有优秀的讲座和免费的电子书。 You won't regret it! 你不会后悔的!

Google around :) and maybe, you'll come back to answer your own question in a few days. 谷歌周围:)也许,你会在几天后回来回答你自己的问题。

Happy coding! 快乐的编码!

Others have commented on your confusion about terminology. 其他人评论了你对术语的困惑。 I'll comment on your code. 我会评论你的代码。

When you do: 当你这样做时:

myObj* var = new myObj;
var = other1;

you're creating a memory leak . 你正在创造一个内存泄漏 new myObj allocated memory for a structure, and set var to point there. new myObj为结构分配内存,并将var设置为指向那里。 When you then reassign var , you no longer have a variable pointing to the structure that was allocated. 然后,当您重新分配var ,您不再有指向已分配结构的变量。 C++ does not have automatic garbage collection, so this memory is no longer accessible, but you also don't have a variable that you can use with delete to reclaim it. C ++没有自动垃圾收集,因此不再可以访问此内存,但您也没有可以使用delete来回收它的变量。

var = other1 reassigns the pointer, it does not copy the contents; var = other1重新分配指针,它复制的内容; if you want to copy structures, you must write: 如果你想复制结构,你必须写:

*var = *other1;

When you then do: 当你这样做:

delete var;

you're not deleting the original structure, you're deleting whatever other pointed to. 你没有删除原始结构,你正在删除other指向的结构。 This is only valid if that structure was created using new . 这仅在使用new创建该结构时才有效。

You definitely need to go back and review all your instructional material on pointers in C++. 你肯定需要返回并查看所有关于C ++指针的教学材料。

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

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