Skip to content

Commit a6abc94

Browse files
committed
Merge #17281: doc: Add developer note on c_str()
1cf9b35 doc: Add developer note on c_str() (Wladimir J. van der Laan) Pull request description: Add a note when to use and when not to use `c_str()`. ACKs for top commit: elichai: ACK 1cf9b35 MarcoFalke: Looking nice ACK 1cf9b35 Tree-SHA512: 38cb5e54695782c23a82d03db214a8999b5bb52553f4fbe5322281686f42616981a217ba987feb6d87f3e6b95919cadd8484efe69ecc364ba1731aaf173626c9
2 parents 3c40bc6 + 1cf9b35 commit a6abc94

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

doc/developer-notes.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,28 @@ Strings and formatting
640640

641641
- *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion.
642642

643+
- Use `.c_str()` sparingly. Its only valid use is to pass C++ strings to C functions that take NULL-terminated
644+
strings.
645+
646+
- Do not use it when passing a sized array (so along with `.size()`). Use `.data()` instead to get a pointer
647+
to the raw data.
648+
649+
- *Rationale*: Although this is guaranteed to be safe starting with C++11, `.data()` communicates the intent better.
650+
651+
- Do not use it when passing strings to `tfm::format`, `strprintf`, `LogPrint[f]`.
652+
653+
- *Rationale*: This is redundant. Tinyformat handles strings.
654+
655+
- Do not use it to convert to `QString`. Use `QString::fromStdString()`.
656+
657+
- *Rationale*: Qt has build-in functionality for converting their string
658+
type from/to C++. No need to roll your own.
659+
660+
- In cases where do you call `.c_str()`, you might want to additionally check that the string does not contain embedded '\0' characters, because
661+
it will (necessarily) truncate the string. This might be used to hide parts of the string from logging or to circumvent
662+
checks. If a use of strings is sensitive to this, take care to check the string for embedded NULL characters first
663+
and reject it if there are any (see `ParsePrechecks` in `strencodings.cpp` for an example).
664+
643665
Shadowing
644666
--------------
645667

0 commit comments

Comments
 (0)