小编Jos*_*uel的帖子

通过C++ 11 lambda中的引用捕获静态变量

主要问题

我正在尝试使用GCC 4.7.2编译以下代码:

#include <iostream>

int foo() {
    static int bar;
    return [&bar] () { return bar++; } (); // lambda capturing by reference
}

int main (int argc, char* argv[]) {
    std::cout << foo() << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

似乎进展不顺利,因为输出是这样的:

$p2.cpp: In function ‘int foo()’:
$p2.cpp:6:14: warning: capture of variable ‘bar’ with non-automatic storage duration [enabled by default]
$p2.cpp:4:16: note: ‘int bar’ declared here
Run Code Online (Sandbox Code Playgroud)

所以,我的第一个问题是:

这是GCC的失败,还是代码不合法​​C++ 11?这在GCC的最新版本中是否已修复?

在shared_ptr工厂中使用技巧

我考虑使用非文字静态变量构建基于此原理的工件.此工件旨在成为shared_ptr <T>对象的工厂,当您只需要为同一实例使用重复的shared_ptr容器时,它可以避免创建新的T对象.

这个工件看起来像:

std::shared_ptr<Foo> create(std::string name) {
    static std::unordered_map<std::string,std::weak_ptr<Foo>> registry;

    if …
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++11

37
推荐指数
2
解决办法
2万
查看次数

在静态变量定义中捕获的引用

#include <iostream>

void foo(int k) {
    static auto bar = [&]{
        std::cout << k << std::endl;
    };
    bar();
}

int main () {
    foo(1); foo(2); foo(3); // output is correct: 1, 2, 3
}
Run Code Online (Sandbox Code Playgroud)

检查函数foo,静态lambda如何通过引用捕获k.这似乎有效,并且更复杂的数据类型而不是int也会发生同样的情况.

这是预期的吗?是否保证每次调用fook的地址都相同,或者这个UB是什么?

在此先感谢,如果之前已经回答,我很抱歉(我确实试图找到类似的问题而没有成功)

c++ c++11

8
推荐指数
1
解决办法
168
查看次数

为什么这个移动构造函数如此贪婪?

我有以下代码:

#include <iostream>

class foo_class {
    std::string value;
public:
    foo_class(const foo_class& v) : value{v.value} {
        std::cout << "copy constructor" << std::endl;
    }

    foo_class(foo_class&& v) : value{std::move(v.value)} {
        std::cout << "move constructor" << std::endl;
    }

    ~foo_class() {
        std::cout << "destructor" << std::endl;
    }

    foo_class(std::string v) : value{std::move(v)} {
        std::cout << "type constructor" << std::endl;
    }
};

struct Data {
    foo_class a;
    foo_class b;
};

int main() {
    std::string c = "3";
    Data x{c,c+"3"};
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

重要的是,我使用GCC和Clang(分别为4.8.2和3.4)和标志-fno-elide-constructors进行编译,因此我们不会忽略复制/移动构造函数.

执行结果如下: …

c++ copy-constructor move-constructor move-semantics c++11

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