Consider the following code based on this answer :
#include <iostream>
#include <sstream>
class StringBuilder {
public:
template <typename T> inline StringBuilder &operator<<(T const &t) {
ss << t;
return *this;
}
inline char const * c_str() {
return ss.str().c_str();
}
private:
std::stringstream ss;
};
void foo(const char *x) {
std::cout << x << std::endl;
}
int main() {
foo((StringBuilder() << "testing " << 12 << 3 << 4).c_str());
return 0;
}
Does a call foo()with a temporary return value StringBuilderallow UB to be called?
The reason why I ask is that the above example works fine, but in real life I use a library that, among other things, contains logging tools, and using this library, I get the wrong output (logging function accepts mine is char*correct, but it overwrites it internally, which made me believe that the memory is no longer valid).
source
share