首页 > 解决方案 > 在容器中引用?

问题描述

当它在容器中时,我在将字符串作为对 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 foo;
  };

  auto foo = codegen1({3, "text"});
  auto foo2 = codegen2(3, "text");
  std::cout << foo->txt;
} 

我知道要走的路是使用const std::pair<int, std::string>&,但我想了解为什么这种方法不起作用。

标签: c++reference

解决方案


第 1 部分:这看起来一目了然。

"text"不是字符串,它是用于创建临时std::string对象的文字,然后用于初始化std::pair. 因此,您会认为仅暂时需要的字符串(即仅在std::pair构造之前)在被引用时消失是有意义的。

第 2 部分:但它不应该被破坏。

但是,作为表达式的一部分创建的临时对象应该保证在当前“完整表达式”结束之前有效(简化:直到分号)。

这就是为什么调用codegen2()工作正常。一个临时std::string的被创建,并且它保持活动状态直到调用codegen2()完成。

第 3 部分:在这种情况下,它被破坏了。

那么为什么在codegen1()'s 的情况下字符串会过早地被破坏呢?"text"从to的转换std::string不是作为子表达式发生的,而是作为使用其自己的范围调用的单独函数的一部分发生的。

这里使用的构造函数std::pair是:

// Initializes first with std::forward<U1>(x) and second with std::forward<U2>(y).
template< class U1 = T1, class U2 = T2 >
constexpr pair( U1&& x, U2&& y );

构造函数"text"作为参数获取,并且在构造函数内部std::string完成了的构造,因此当我们从该构造函数返回时,作为该过程的一部分创建的临时变量将被清除。std::pair

有趣的是,如果该构造函数不存在,std::pair' 的基本构造函数:pair( const T1& x, const T2& y );会处理得很好。隐式转换std::string将在调用构造函数之前完成。

我们如何解决这个问题?

有几种选择:

强制转换发生在正确的“级别”:

auto foo = codegen1({3, std::string("text")});

实际上是同一件事,但语法更好:

using namespace std::literals::string_literals;
auto foo = codegen1({3, "text"s});

使用 a std::string_view,它完全不需要转换:

auto codegen1 = [](std::pair<int, std::string_view> package) -> Foo* {
...
}

虽然,在你的情况下,因为Foo将获得字符串的所有权,通过值传递它并移动它显然是要走的路(我也冒昧地清理一下代码):

struct Foo {
  Foo(int num, std::string txt)
    : num(num)
    , txt(std::move(txt))
  {}

  int num;
  std::string txt;
};

int main()
{
  auto codegen1 = [](std::pair<int, std::string> package) {
    return std::make_unique<Foo>(package.first, std::move(package.second));
  };

  auto foo = codegen1({3, "text"});

  std::cout << foo->txt;
}

推荐阅读