Nikolai
Nikolai

Reputation: 3134

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?

Upvotes: 4

Views: 2781

Answers (1)

GManNickG
GManNickG

Reputation: 503805

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.)

Upvotes: 7

Related Questions