简体   繁体   English

C ++指针和内存释放

[英]C++ Pointers and Memory Deallocation

I'm less used to rigid type-checking and lower level stuff such as deallocation. 我不太习惯严格的类型检查和较低级别的东西,例如释放。 Recently, while attempting to write something along the lines of 最近,在尝试按照以下方式写东西时

// Product is a struct I defined earlier, nothing fancy
vector<string, Product>::iterator it;
// Do some stuff with the iterator...
// And now I know I won't be using the iterator again
map<string, Product>::iterator it;

However, this yielded the error 'duplicate declaration of local variable "it"'. 但是,这产生了错误“局部变量“ it”的重复声明”。 So my question then is simply, why did this happen? 所以我的问题就是,为什么会这样? I researched memory deconstruction, but so far as I'm aware it's apparently impossible to deconstruct iterators because they're actually pointers? 我研究了内存解构,但据我所知,显然不可能解构迭代器,因为它们实际上是指针? Does C++ really not allow you to use the same name for different variables if you know you won't need the old one again, or normally would you release them into memory? 如果您知道不再需要旧的变量,C ++真的不允许您对不同的变量使用相同的名称吗?或者通常您会将它们释放到内存中吗?

Since it is in the same scope , it cannot be re-declared: variable shadowing does not apply in the same scope. 由于it在同一范围内 ,因此无法重新声明:变量阴影不适用于同一范围。

One way round this is to use scoping blocks: 一种解决方法是使用作用域块:

// Product is a struct I defined earlier, nothing fancy
{
    vector<string, Product>::iterator it;
    // Do some stuff with the iterator...
    // And now I know I won't be using the iterator again
}

{
    map<string, Product>::iterator it;
    // However, this yielded the error 'duplicate declaration 
    // Not any more!
}

In C++ you actually only need one of the scoping blocks but that could be construed as an obfuscating asymmetry. 实际上,在C ++中,您仅需要作用域块之一,但是可以将其解释为混淆的不对称性。 Java attempts to sort this out but fails miserably in that you can remove the second pair but not the first! Java试图解决这个问题,但是惨败,因为您可以删除第二对而不是第一对!

It doesn't matter what language you use, if you give two different variables the same name in the same scope (and they are meant to be different things) you will just [edit] confuse everyone who comes along after you (including in this case yourself). 不管使用哪种语言,如果在相同范围内为两个不同的变量赋予相同的名称(它们的意思是不同的东西),您将[编辑]混淆后面的每个人(包括此变量)案例)。 And that counts double for people who have to maintain your code. 对于需要维护您的代码的人来说,这是至关重要的。

Get out of that habit as soon as possible. 尽快摆脱这种习惯。 It doesn't matter what the language offers you. 语言为您提供什么都无所谓。 Just don't do it. 只是不要这样做。

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

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