简体   繁体   中英

Why I cannot use a string output from a function without creating a string variable?

I have the code, which works correctly:

#include <iostream>

std::string func()
{
    return "string";
}

int main()
{
    std::string str = func();
    std::cout << str << std::endl;
    return 0;
}

But when I change main function to this, I have no output:

int main()
{
    const char* c = func().c_str();
    std::cout << c << std::endl;
    return 0;
}

This main function works fine:

int main()
{
    std::string str = func();
    const char* c = str.c_str();
    std::cout << c << std::endl;
    return 0;
}

I am using multibyte encoding in the Visual Studio.

Well, your second exampe is Undefined Behavior, due to accessing freed memory. Anything can happen.

func() returns a temporary std::string , whose lifetime ends at the end of the full expression, turning c into a dangling pointer:

const char* c = func().c_str();

Using a dangling pointer, especially dereferencing, is contra-indicated:

std::cout << c << std::endl;

The first example avoids that by storing the return-value in a variable and printing that.
The third by also storing the return-value in a variable, even though it then for some unfathomable reason uses a pointer to the owned sequence for output.

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