0

I encountered some strange behaviour with GCC-4.8 while initializing std::vector within default ctor of class. My code is the following:

class TestLogger final: public Logger
{
public:   
  void LogWarning(const std::string& msg,) const override{
    this->mWarningMessages.emplace_back(msg);
  }

  bool ContainsWarnings() const{
    return !this->mWarningMessages.empty();
  }

private:
  mutable std::vector<std::string> mWarningMessages;  // needs to be mutable because it's changed by const method
};

What happens if I use some object of my class TestLogger? That member mWarningMessages seems to not be initialized.

See following code:

int main(int argc, char *arcv[])
{
  TestLogger logger;
  bool shouldBeFalse = logger.ContainsWarnings() // --> false expected, but returns true;
}

If I implement the default constructor of class TestLogger by myself with mWarningMessages in initializer list, everything works perfect.

Does anybody have a clue why my code without default ctor is not working? I would've expected mWarningMessage to be initialized properly by auto-generated default ctor of my class TestLogger. Might this be a bug in GCC-4.8?

Thanks for your help

Egon Allison
  • 1,329
  • 1
  • 13
  • 22
  • 3
    Did you try other compiler versions? Whatever version ideone.com uses, it produces `false`: https://ideone.com/w2UpL8 – mch Mar 07 '19 at 10:16
  • What if you do `TestLogger() = default;`? – Fantastic Mr Fox Mar 07 '19 at 10:20
  • 3
    Please post a [mcve]. – molbdnilo Mar 07 '19 at 10:26
  • I tried with [GCC 4.7.4](https://godbolt.org/z/1xQ_yV) and [GCC 4.8.1](https://godbolt.org/z/dTl2uH); both behave as expected. Are you on GCC 4.8.0? If so, maybe you got bitten by one of the GCC 4.8.0 release bugs. Either way, consider upgrading to a compiler that is not six years old. – Botje Mar 07 '19 at 10:50
  • After correcting syntax errors in supplied code (extra comma in argument list), removing derivation from non-existent class, and including needed standard headers, I could not reproduce the problem with g++4.8.0. This is unlikely to be a compiler bug - rules for construction of members relevant to your code haven't changed since C++98, which is much older than gcc-4.8 (which supports C++11). Your problem is consistent with a confused IDE, so a different version of some object file than the one you expect is being linked. Try doing a clean build then build from scratch to unconfuse the IDE. – Peter Mar 07 '19 at 10:56
  • Thanks for your answers. I am using GCC 4.8.5. I definitely would like to upgrade to a newer version, but my company doesn't allow this :( Unfortunately `TestLogger() = default;` isn't working either. I also tried clean builds several times. –  Mar 07 '19 at 14:25

0 Answers0