【问题标题】:C++ pointer to variable within if statement指向 if 语句中变量的 C++ 指针
【发布时间】:2013-02-26 16:38:41
【问题描述】:

下面代码的行为让我吃惊:

map<string,long>* map_ptr;
if(true){
    map<string, long> my_map;
    my_map["a"] = 1;
    my_map["b"] = 2;
    my_map["c"] = 3;
    map_ptr = &my_map;
}

//works ONLY IF this for loop comes before the next for loop
for(map<string, long>::iterator itr = map_ptr->begin(); itr != map_ptr->end(); ++itr)
    cout << itr->second << endl; 

// does not work prints random bits
for(map<string, long>::iterator itr = map_ptr->begin(); itr != map_ptr->end(); ++itr)
    cout << itr->first << endl; 

我知道在 if 语句中创建的变量只在其中具有作用域,但我认为声明指向它们的指针会起作用。我对这段代码的堆栈结构了解有限,但我认为变量虽然超出了范围,但仍然在堆栈上,所以它们仍然存在。但似乎发生的事情比我所知道的要多。最让我惊讶的是为什么第一个 for 循环可以正确打印出东西,但前提是它是在第二个 for 循环之前执行的。我想这与类型有关,因为long 是内置的,而string 不是,但这远远不足以解释发生了什么。

请帮助我理解这段代码。谢谢!

【问题讨论】:

  • 一旦变量超出范围,不要尝试访问它!它已经死了(即使编译器可能还没有真正清理它)。
  • 那篇关于酒店钥匙的帖子在哪里...

标签: c++ pointers stack


【解决方案1】:

代码具有未定义的行为,这意味着任何事情都可能发生,包括看起来可以工作,因为map_ptr 是一个悬空指针,因为my_map 将在if 的结束} 处被破坏。 map_ptr 将保留my_map地址,但这不会影响my_map 的生命周期。

【讨论】:

    猜你喜欢
    • 2019-09-10
    • 2014-12-04
    • 2012-11-18
    • 2021-10-15
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    相关资源
    最近更新 更多