当字符串位于容器中时,我在将字符串作为 lambda 的引用传递时遇到问题。我猜当我调用该函数时它会消失(超出范围)init()
,但为什么呢?然后,当我将它作为字符串引用传递时,为什么它不会消失?
#include <iostream>
#include <string>
struct Foo {
void init(int num, const std::string& txt)
{
this->num = num;
this->txt = txt;
}
int num;
std::string txt;
};
int main()
{
auto codegen1 = [](std::pair<int, const std::string&> package) -> Foo* {
auto foo = new Foo;
foo->init(package.first, package.second); //here string goes out of scope, exception
return foo;
};
auto codegen2 = [](int num, const std::string& txt) -> Foo* {
auto foo = new Foo;
foo->init(num, txt);
return …
Run Code Online (Sandbox Code Playgroud)