Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

今日見つけた話ですが、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;
}();
nanashi
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away