cppcheck throws warning on const std::string[]
Asked Answered
G

1

14

I'm struggling with a warning that cppcheck (version 1.85 on a Linux machine) is reporting:

someFile.h:23:29: warning: Redundant code: Found a statement that begins with string constant. [constStatement]
const std::string OffOn[]= {"off", "on"};
^

I did some research and found that changing the statement to

const std::string OffOn[]= {std::string("off"), std::string("on")};

removes the warning. However I do not understand what's going on, and what's "bad" about my first solution. Maybe someone can explain it to me? Or give me some hints!

Gilges answered 1/11, 2018 at 10:23 Comment(3)
Maybe it recomeds you to use initializer_list like: const std::string OffOn[]{"off", "on"};, so = is just unnecessary.Honor
@DenisSablukov that's it! And now it make perfectly sense to me. Thanks a lot!Gilges
I'd actually file an issue report to cppcheck. The warning message produced is really unhelpful.Pyroxenite
H
17

It recommends you use initialization with a braced-init-list like: const std::string OffOn[]{"off", "on"};, so = is just unnecessary.

Honor answered 1/11, 2018 at 10:50 Comment(2)
It's probably nitpicking, but in this context {...} is not a std::initializer_list. It's a braced-init-list.Teak
It's clearly a bug regardless; there's no "redundant code" hereConcepcion

© 2022 - 2024 — McMap. All rights reserved.