gpt4 book ai didi

c++ - 为什么在 lambda 中获取指向成员函数的指针会在 VS2013 上触发警告

转载 作者:行者123 更新时间:2023-11-28 04:55:40 25 4
gpt4 key购买 nike

在 visual studio 2013(安装了更新 5)上编译代码并使用默认警告级别 (/W3)

#include <iostream>

class Foo {
public:
void Thunk()
{
auto lambda = [](Foo* f, const char* msg) {
auto pfn = &Foo::Print; // complained this statement
(*f.*pfn)(msg);
};

lambda(this, "abc");
}

void Print(const char* msg)
{
std::cout << msg << std::endl;
}
};

int main()
{
Foo foo;

foo.Thunk();

return 0;
}

会触发编译警告:

Line 16: warning C4573: the usage of 'Foo::Print' requires the compiler to capture 'this' but the current default capture mode does not allow it

但是,如果我在 Visual Studio 2017 (ver15.4.2) 上编译这段代码,这个警告就会消失;并使用/W4 警告级别编译仍然无法重现警告。

这是 Visual Studio 2013 的实现错误吗?

最佳答案

发生这种情况是因为您在 lambda 声明中有默认的捕获选项。只需检查 Lambda 捕获 部分 here

我认为你应该用 [=]

来改变它
auto lambda = [=](Foo* f, const char* msg) {
auto pfn = &Foo::Print; // complained this statement
(*f.*pfn)(msg);
};

从上面的链接中,这是可能的捕获选项:

captures - a comma-separated list of zero or more captures, optionally beginning with a capture-default.

  • [a,&b] where a is captured by copy and b is captured by reference.
  • [this] captures the current object (*this) by reference
  • [&] captures all automatic variables used in the body of the lambda by reference and current object by reference if exists
  • [=] captures all automatic variables used in the body of the lambda by copy and current object by reference if exists
  • [] captures nothing

A variable can be used without being captured if it does not have automatic storage duration (i.e. it is not a local variable or it is static or thread local) or if it is not odr-used in the body of the lambda.

关于c++ - 为什么在 lambda 中获取指向成员函数的指针会在 VS2013 上触发警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47177263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com