7

我已经成功编写了一个像这样的类,在定义为所述类的非静态属性的 lambda 中捕获它:

#include <memory>
#include <iostream>
#include <functional>

struct S
{
  S()
  {
    std::cout << "S::S()[" << this << "]" << std::endl;
  }

  std::string y_{"hi mate"};
  int x_;
  std::function<void(int*)> del_{[this](int *ptr)
  {
    std::cout << "Deleting ptr[" << ptr << "] this[" << this << "] this->y_[" << this->y_ << "]" << std::endl;
  }};
  std::unique_ptr<decltype(x_), decltype(del_)> unique_{&x_, del_};
};

int main()
{
  S s;
}

这编译并且似乎运行得很好。

但是,使用模板类,它不再起作用:

#include <memory>
#include <iostream>
#include <functional>

template <typename>
struct S
{
  S()
  {
    std::cout << "S::S()[" << this << "]" << std::endl;
  }

  std::string y_{"hi mate"};
  int x_;
  std::function<void(int*)> del_{[this](int *ptr)
  {
    std::cout << "Deleting ptr[" << ptr << "] this[" << this << "] this->y_[" << this->y_ << "]" << std::endl;
  }};
  std::unique_ptr<decltype(x_), decltype(del_)> unique_{&x_, del_};
};

int main()
{
  S<int> s;
}

$> g++ -std=c++1y custom_deleter_template.cpp
~/test custom_deleter_template.cpp:在'struct S::'的实例化中:custom_deleter_template.cpp:9:3:来自'S< >::S() [ with = int]' custom_deleter_template.cpp:24:10:
从这里需要 custom_deleter_template.cpp:15:35:内部编译器错误:在 tsubst_copy 中,在 cp/pt.c:12569
std::function del_{[this](int *ptr) ^ 请提交完整的错误报告,并在适当的情况下提供预处理源。有关说明,请参阅。存储在 /tmp/pyro/ccxfNspM.out 文件中的预处理源,请将其附加到您的错误报告中。

在提交错误报告之前(我不能这样做,他们阻止了帐户创建),根据标准所说,它不编译是否正常?

编译器是 g++ (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2,使用标志 -std=c++1y。标志 -std=c++11 也会发生同样的事情。

4

1 回答 1

0

这确实是 GCC 中的一个 bug,已经在跟踪中。

它似乎影响 4.8 和 4.9。正如评论中所指出的,这个特定的例子适用于 4.7 和 5.0。您可以在这里亲自查看并使用不同版本的 gcc。

然而,这个没有外部依赖的代码的简化版本仍然会在 5.0 中崩溃:

template <typename>
struct S {
  int f{[this](){return 42;}()};
};

int main(){
    return S<int>{}.f; //  should return 42
}

我建议您在使用您的代码之前等待我引用的错误被修复,或者切换到另一个编译器;)。

于 2015-03-07T10:10:46.450 回答