简体   繁体   中英

Passing pointer to a temporary std::string to another thread

Consider the following C++ program

#include <iostream>
#include <thread>
#include <string>

std::string getString() {
    return "hello world";
}

void printString(const char* s)
{
    std::cout << s << std::endl;
}

int main()
{       
    std::thread T(printString, getString().c_str());

    T.join();

    return 0;

}

The call to getString() will return a temporary std::string and the value getString().c_str() is a pointer to a temporary stack variable.

Since each thread has its own stack (but share the heap) then passing a pointer to a string on the main thread to some thread T shouldn't work in theory right?

Why does this code compile and run to print hello world ? Or am I running into some kind of undefined behavior?

EDIT:

What if the program looks like this (no threads)

#include <iostream>
#include <thread>
#include <string>

std::string getString() {
    return "hello world";
}

void printString(const char* s)
{
    std::cout << s << std::endl;
}

int main()
{       
    printString(getString().c_str());                
    return 0;

}

Or am I running into some kind of undefined behavior?

That is exactly what happens. The string that was returned from getString only lives until the end of the epxresion

std::thread T(printString, getString().c_str());

That means that in printString you have a pointer to data that is no longer valid. You might get what it contained, or something else can happen. Accessing the pointer is undefined behavior so any result you get is "correct".


If you change getString to

const char * getString() {
    return "hello world";
}

and the create the thread like

std::thread T(printString, getString());

Then this would be okay since "hello world" has static storage duration so it will live for the rest of the life of the program

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