小编Mat*_*Mat的帖子

容器中的引用?

当字符串位于容器中时,我在将字符串作为 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)

c++ reference

10
推荐指数
1
解决办法
962
查看次数

标签 统计

c++ ×1

reference ×1