我读到字符串文字具有静态存储持续时间,这是否意味着对它们的引用始终有效?例如,以下代码是否安全:
std::function<void()> foo(const std::string& name){
// capture name by reference
return [&](){
std::cout<<"The name is "<<name<<std::endl;
};
}
int main() {
std::function<void()> func;
{
func = foo("test");
func(); // func called in the same scope
}
func(); // func called in the outer scope
}
如果我们首先根据该字符串文字创建一个字符串,然后引用该字符串,结果会怎样?
std::function<void()> foo(const std::string& name){
// capture name by reference
return [&](){
std::cout<<"The name is "<<name<<std::endl;
};
}
int main() {
std::function<void()> func;
{
std::string test = "test";
func = foo(test);
func(); // func called in the same scope
}
func(); // func called in the outer scope
}