简体   繁体   中英

C++11 type deduction vs const char *

In GotW 94 , Herb Sutter draws a distinction between the "classic C++" declaration

const char* s = "Hello";

and the "modern" style

auto s = "Hello";

He tells us that there's a "subtle difference in the type of s , where the auto style is more correct". [Edited to add: comments suggest that this might not be a fair representation of what Sutter actually meant; see discussion below.]

But... what's the difference? I was under the impression that a const char * is the correct way to refer to a string literal. Further, when I asked my debugger (lldb), it seems to think the types are actually the same:

* thread #1: tid = 0x1756c2, 0x0000000100000f8f test`main + 31 at test.cc:4, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x0000000100000f8f test`main + 31 at test.cc:4
   1    int main(void) {
   2        const char* s = "Hello";
   3        auto t = "Hello";
-> 4        return 0;
   5    }
(lldb) fr v
(const char *) s = 0x0000000100000f91 "Hello"
(const char *) t = 0x0000000100000f91 "Hello"

Where's the subtle difference Sutter refers to?

I posted this to Herb Sutter :

What do you think is the “subtle difference in the type of s, where the auto style is more correct”? See C++11 type deduction vs const char *

And here's his reply:

I think I had in mind that the auto version deduced an array, which it doesn't. If I had something else in mind, I've forgotten it now, so I've removed that phrase and added your moniker to the Acknowledgments. Thanks for the feedback!

你并不完全清楚赫伯所说的(背景很重要),但无论如何,类型是相同的。

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