简体   繁体   中英

C++ Stringstream initializations

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM