【发布时间】:2018-11-19 14:25:58
【问题描述】:
我一直在阅读Lambda capture as const reference?
这是一个有趣的功能,有时我也希望这个功能存在,尤其是当我有大量数据时,我需要在 lambda 函数中访问这些数据。
我的后续问题 -
- 我们应该通过 lambda 中的 const 引用来捕获吗?如果是,它应该如何表现?
(编辑 - 我也对捕获变量的生命周期的行为感兴趣。) - 在 C++ 语法中引入它有什么可能的缺点吗?(我想不出来)
假设我们可以。
我们假设[const &] 是要捕获的语法。
int x = 10;
auto lambda = [const & x](){ std::cout << x << std::endl; };
lambda(); // prints 10, great, as expected
x = 11;
lambda(); // should it print 11 or 10 ?
我的直觉是它的行为应该像[&],但不应该允许修改捕获的值。
template<typename Func>
void higher_order_function(int & x, Func f)
{
f(); // should print 11
x = 12;
f(); // should print 12
}
void foo()
{
int x = 10;
auto c = [const & x] () { std::cout << x << std::endl; };
c(); // should print 10
x = 11;
c(); // should print 11
higher_order_function(x, c);
auto d = [const & x] () { x = 13; }; // Compiler ERROR: Tried to assign to const qualified type 'const int &'!
}
【问题讨论】:
-
您对
const的含义犯了一个常见错误。const没有描述一个值——只有一个特定的符号。它不表示“值不会改变”。这意味着“这个特定的符号不会改变值” -
尝试编译时 (clang++ -std=c++14) 我收到此错误:
expected variable name or 'this' in lambda capture list。我怎样才能编译这个? (我删除了最后一条语句)。
标签: c++ c++11 closures c++14 constants