Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I copy-initialize a stringstream from a string?

The following code fails in GCC, Clang and Visual Studio:

#include <string>
#include <sstream>

int main() {
    std::string s = "hello"; // ok, copy-initialization
    std::stringstream ss1(s); // ok, direct-initialization
    std::stringstream ss2 = s; // error
}

I thought the only case where direct-initialization works while copy-initialization doesn't is when the constructor is explicit, which it is not in this case. What's going on?

like image 419
Nikolai Avatar asked Mar 23 '23 00:03

Nikolai


1 Answers

That constructor is marked explicit, so can only be used with direct-initialization. §27.8.5:

explicit basic_stringstream(
ios_base::openmode which = ios_base::out | ios_base::in);

explicit basic_stringstream(
const basic_string<charT,traits,Allocator>& str,
ios_base::openmode which = ios_base::out | ios_base::in);

basic_stringstream(const basic_stringstream& rhs) = delete;

basic_stringstream(basic_stringstream&& rhs);

(The same is true for basic_stringbuf, basic_istringstream, and basic_ostringstream.)

like image 79
GManNickG Avatar answered Mar 31 '23 22:03

GManNickG