1

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
nz_21
  • 6,140
  • 7
  • 34
  • 80

1 Answers1

4

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405