当我使用 lambda 表达式时,有时我会移动捕获可复制和可移动的对象。在下面的示例中,对象是t
,其类型是 tracer
。在lambda表达式中,我想再次将t
移动到其他函数f()
。 f()
的参数是按值传递的,因为我想同时支持复制和移动f()
。
main()
的第一部分我称之为f(std::move(t))
但它没有被移动而是被复制t
,因为它被捕获为常量变量。main()
函数的第二部分,我添加到 lambda 表达式的mutable
。它按我的预期工作。
我经常忘记在 lambda 表达式中添加mutable
。如果t
是仅移动类型,则第一种情况会产生编译错误。我很容易注意到这个问题。但是,如果t
是可复制和可移动的,我很难注意到意外的复制。我想检查一下这种情况。
有什么好方法可以做到这一点吗?
#include <iostream>
struct tracer {
tracer() {
std::cout << __PRETTY_FUNCTION__ << ":" << this << std::endl;
}
~tracer() {
std::cout << __PRETTY_FUNCTION__ << ":" << this << std::endl;
}
tracer(tracer const& other) {
std::cout << __PRETTY_FUNCTION__ << ":" << this << " <- " << &other << std::endl;
}
tracer(tracer&& other) {
std::cout << __PRETTY_FUNCTION__ << ":" << this << " <- " << &other << std::endl;
}
tracer& operator=(tracer const& other) {
std::cout << __PRETTY_FUNCTION__ << ":" << this << " <- " << &other << std::endl;
return *this;
}
tracer& operator=(tracer&& other) {
std::cout << __PRETTY_FUNCTION__ << ":" << this << " <- " << &other << std::endl;
return *this;
}
};
void f(tracer) {
}
int main() {
{
tracer t;
// move assign capture
[t = std::move(t)] { // forget write mutable
f(std::move(t)); // I expect move but copy due to lack of mutable
}();
}
std::cout << "---" << std::endl;
{
tracer t;
// move assign capture
[t = std::move(t)] () mutable {
f(std::move(t)); // Moved as I expected
}();
}
}
运行演示:https://wandbox.org/permlink/vphaVOXYhN0sr42o
我想出了一个解决方案。我为std::move()
写了以下包装器。
template <typename T>
typename std::remove_reference_t<T>&&
only_move(T&& t) {
static_assert(!std::is_const_v<std::remove_reference_t<T>>, "T is const. Fallback to copy.");
return std::move(t);
}
我用only_move()
替换了std::move()
,如下所示:
int main() {
{
tracer t;
// move assign capture
[t = only_move(t)] { // got static assertion failed *1
f(only_move(t)); // I expect move but copy due to lack of mutable
}();
}
std::cout << "---" << std::endl;
{
tracer t;
// move assign capture
[t = only_move(t)] () mutable {
f(only_move(t)); // Moved as I expected
}();
}
}
然后,只有当我忘记mutable
时,我才收到静态断言失败消息。
*1 错误:static_assert由于要求"!std::is_const_v"T 是常量。 回退到复制。
运行演示:https://wandbox.org/permlink/3HlrAab0IAUYQON8