LoginSignup
22
22

More than 5 years have passed since last update.

c++11のラムダ式でグローバル変数を初期化

Last updated at Posted at 2014-10-20

今日見つけた話ですが、c++のラムダ式は変数の初期化にも使えますね。

test.h
extern const std::string global_str;
test.cpp
const std::string global_str = [] {
    std::string str;
    str.append("abc");
    return str;
}();

さらに驚くことに、静的変数を初期化する場合そのラムダ式内では所在クラスのプライベート関数をアクセスできます。

test.h
class test_class {
    test_class() {};
public:
    const static test_class single_obj;
};
test.cpp
const test_class test_class::single_obj = [] {
    test_class obj;
    return obj;
}();
22
22
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
22