我知道这是一个相当常见的问题,但对于我来说仍然很新奇!
我不理解悬空指针的概念,一直在Google上搜索,并编写测试方法来寻找。
我只是想知道这是否是一个悬空指针?因为我找到的所有例子都返回了某个值,而我正在尝试类似的操作!
谢谢!
void foo(const std::string name)
{
// will it be Dangling pointer?!, with comments/Answer
// it could be if in new_foo, I store name into Global.
// Why?! And what is safe then?
new_foo(name.c_str());
}
void new_foo(const char* name)
{
// print name or do something with name...
}
new_foo
用于比foo
更全局的地方来存储指针,你就应该是安全的。 - Benjamin Lindleyconst char *foo(string name) { return name.c_str(); }
,因为当foo
退出时,“name”消失了。 - JoshG79foo
的返回类型,以避免因为说你正在做的事情是100%安全和正确而显得愚蠢。 - Benjamin Lindley