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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…