C++ Stringstream initializations

623 views Asked by At

I have two code snippets:

This does not compile:


std::string reverseSentence(std::string sentence) {
    std::stringstream stream = sentence;
}

This does:

std::stringstream stream (sentence);

It's my understanding that T foo = expr is T foo(expr). Thus, aren't the two stringstream initializations equivalent? Why is one compiling and the other not?

1

There are 1 answers

0
leslie.yao On BEST ANSWER

The constructor of std::basic_stringstream taking std::string is marked as explicit, it's not considered in copy initalization like std::stringstream stream = sentence;.

std::stringstream stream (sentence); is direct initialization, which considers explicit constructors too.

Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-explicit constructors and non-explicit user-defined conversion functions, while direct-initialization considers all constructors and all user-defined conversion functions.