std::string::c_str() and temporaries

前端 未结 3 1719
独厮守ぢ
独厮守ぢ 2020-11-28 07:22

Is the following C++ code well-formed:

void consumer(char const* p)
{
  std::printf(\"%s\", p);
}

std::string random_string_generator()
{
  // returns a ran         


        
3条回答
  •  爱一瞬间的悲伤
    2020-11-28 08:06

    The temporary std::string's lifetime extends just beyond the point where consumer returns, so it is safe to use anything on that string directly from within consumer. What is not OK is to store the value that c_str returns and try to use it later (the temporary will have been destroyed, and we can only guess what you will find at the other end of the pointer).

提交回复
热议问题