C ++指针和内存释放

时间:2018-06-01 13:45:40

标签: c++ iterator

我不太习惯严格的类型检查和较低级别的东西,例如释放。最近,在尝试按照

的方式写一些东西时
// 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;

然而,这产生了错误&#39;重复声明的局部变量&#34;它&#34;&#39;。所以我的问题很简单,为什么会这样呢?我研究了内存解构,但据我所知,它显然不可能解构迭代器,因为它们实际上是指针?如果您知道自己不再需要旧的变量,或者通常会将它们释放到内存中,C ++是否真的不允许您对不同的变量使用相同的名称?

2 个答案:

答案 0 :(得分:4)

由于it位于同一范围内,因此无法重新声明:变量 shadowing 不适用于同一范围。

这方面的一个方法是使用范围块:

// 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!
}

在C ++中,您实际上只需要一个范围块,但这可能被视为混淆不对称。 Java尝试对此进行排序,但失败的原因在于您可以删除第二对但第一对!

答案 1 :(得分:-4)

使用哪种语言并不重要,如果你在同一范围内给出两个不同的变量同名(并且它们意味着不同的东西),你只会[编辑]混淆所有出现的人你(在这种情况下包括你自己)。对于那些必须维护代码的人来说,这个数字会增加一倍。

尽快摆脱这种习惯。语言为您提供的内容并不重要。不要这样做。