小编puh*_*acz的帖子

clang - shared_ptr无法运行其删除器

使用(yield ,这是我期望的)构建时,此代码打印0(没有优化)或666(在启用优化的情况下).当lambda通过通用引用传递时,问题就消失了.clang++ -std=c++11-O3666

仅供参考,GCC打印666我测试过的所有版本.

它是编译器错误还是代码不正确?

#include <memory>
#include <iostream>

template <typename T>
std::shared_ptr<void> onScopeExit(T f)
{
    return std::shared_ptr<void>((void*)1, [&](void *) {
        f();
    });
}

struct A {
  void f() {
    auto scopeGuard = onScopeExit([&]() { i = 666; }); //  [1]
    // ... (some work)
  } // (lambda [1] being ? called on scope exit)

  int i = 0;
};

A a;

int main() {
  a.f();
  std::cout << a.i << std::endl; …
Run Code Online (Sandbox Code Playgroud)

c++ lambda clang shared-ptr c++11

3
推荐指数
1
解决办法
82
查看次数

标签 统计

c++ ×1

c++11 ×1

clang ×1

lambda ×1

shared-ptr ×1