vector of structs inline initialization. braced-init-list

爱⌒轻易说出口 提交于 2019-12-25 00:23:20

问题


I ran into a strange issue which unfortunately, I cannot reproduce outside my application itself. The situation is as below. I have the following struct.

struct Foo {
    std::string first;
    std::string second;
    bool flag;
    float value;
};

One of my classes has a member std::vector<Foo> fooList which undergoes the following set of operations periodically.

void someOperation() {
    UpdateFooList(); //< Updates existing members of fooList
    UseFooList(); //< Do some useful stuff with the new values.
    fooList.clear();

    // Repopulate fooList which is where the problem is. The call below
    // has never worked here. It results in either junk values 
    // in fooList[0] or some of the member values at [0] before the clear() call
    // appear to be retained after the emplace_back
    fooList.emplace_back(Foo{"First", "Second", true, 0.0f}); 
}

Here are the things I have tried.

  • To make sure there was no data corruption, tried putting in mutexes everywhere there is an access to fooList.
  • Tried creating a 4 value ctor to Foo with the signature Foo(const std::string&, const std::string&, bool, float) and used this ctor instead of the brace-init-list. No luck here.
  • Tried replacing emplace_back with push_back in the code above. This did not help either.
  • Tried reproducing these problems in an isolated cpp file and it works exactly as expected.

The only thing that appears to work in the application is if I replace the emplace_back with the following two lines.

auto fooEntry = Foo{"First", "Second", true, 0.0f};
fooList.push_back(fooEntry); //< This works as expected.
fooList.emplace_back(fooEntry); //< This also works as expected

Any thoughts on why the inline calls of fooList.emplace_back(Foo{"First", "Second", true, 0.0f}); does not work?

I am on gcc-7.2.0 and the application is compiled using c++14 standards.

While this bit of information may not be relevant adding it here for completeness. The class under consideration is compiled using c++14 and exposed via a .so file, while the application itself is compiled using c++17 and loads the .so. The members of the class under consideration are not exposed outside the class. Just the class methods are public.

来源:https://stackoverflow.com/questions/53161886/vector-of-structs-inline-initialization-braced-init-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!