3 ms·
> It will even print std::string’s correctly if you cast them to const char* by hand What does that mean? I think `print str.c_str()` has worked for me in GDB
by scintill76 2y ago
> It will even print std::string’s correctly if you cast them to const char* by hand
What does that mean? I think `print str.c_str()` has worked for me in GDB before, but sounds like you did something different.
- deleted 2y ago[deleted]
- mananaysiempre 2y agoI was observing that `p (const char *)str` also worked in my experiment, but I’m far from a C++ expert and upon double-checking this seems to have been more of an accident than intended behaviour, because there is no operator const_pointer in basic_string that I can find. Definitely use `p str.c_str()`.
- twoodfin 2y agoIf your std::string was using a short string optimization, that would explain the “accident”. Some implementations even put char[0] at the first byte in the optimized form.
- scintill76 2y agoThat explanation doesn't work IMO, unless `str` is a std::string pointer, which is contrary to the syntax GP suggested with `str.c_str()`. It doesn't seem possible in actual C++ that the cast from non-pointer to pointer would work at all (even if a small string happens to be inlined at offset 0.) Like GP, I looked for a conversion operator, and I don't think it's there. Maybe it is a feature of the gdb parser.
- twoodfin 2y agoGood point, but if it’s a long string, 2/3 of the most common implementations would make the first word the c_str()-equivalent pointer: https://devblogs.microsoft.com/oldnewthing/20240510-00/?p=109742 https://devblogs.microsoft.com/oldnewthing/20240510-00/?p=10...
- fluoridation 2y agoSo it's actually printing *(const char **)&s?
- twoodfin 2y agoThe first pointer-sized chunk of the string structure is a pointer to the C-string representation. So the cast works as written.
- fluoridation 2y agoWell, no, because (const char *)str is nonsense, if str is an std::string.
- twoodfin 2y agoNot to the debugger. If the first 8 bytes of the object referenced by str is a char* the debugger is perfectly capable of using it that way.