Re: Bad use of stringstream temporary?
On 24 Mrz., 17:08, K. Frank wrote:
The basic question is whether the following line of code
is legal and good (according to the current standard):
std::string s1 =
dynamic_cast<std::stringstream&>(std::stringstream() << "abc").str();
static_cast is fine in this case.
The problem is that "abc" gets rendered as a hex pointer
value, rather than as "abc".
I could see why this happens. There are a couple of overloads for
operator<<. Some of them are member functions (which can be called
even on a temporary) and some of them are free functions which take a
non-const reference (and hence require an lvalue, lvalue !=
temporary).
As it turns out operator<<(ostream&, const char*) is a free function
which won't be part of the overload set since you cannot bind a
temporary to this non-const lvalue reference. On the other hand,
ostream::operator<<(const void*) is a member function and a viable
candidate. So, this is what happens:
- array-to-pointer standard conversion (const char[4] --> const char*)
- implicit pointer conversion (const char* --> const void*)
- member function taking the const void* as argument is selected
To avoid this issue and to shorten the code you could wrap a
stringstream object in a custom class type:
struct any2str {
std::stringstream ss;
template<class T>
any2str& operator<<(T const& x) {ss<<x; return *this;}
operator std::string() const {return ss.str();}
};
std::string s1 = any2str() << "abc";
SG