c++ - Returning a C string in a constexpr function: why no warning from the compiler? -


consider following code:

constexpr auto f() {     auto str = "hello world!";     return str; }  int main(int argc, char* argv[]) {     static constexpr auto str = f();     std::cout << str << std::endl;     return 0; } 

is normal compiler not display warning? defined behavior? have guarantee program display "hello world!"? expect "hello world!" not live beyond scope of function...

in c++ string literals have static storage duration , live long program runs. so, pointer string literal returned f valid. no allocation or deallocation involved.

note string literals have type const char[n], in case decays const char * due auto type deduction. if intent use std::string, can directly construct it

auto str = std::string("hello world!"); 

or use operator""s:

using std::string_literals; auto str = "hello world!"s; 

however, since std::string not literal type, values cannot constexpr anymore.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -