mike mike - 1 year ago 54
C++ Question

Does this code causes UB?

I have checkd gcc and clang and both does not generate any warnings. I suppose that lifetime of temporary from foo() will be prolonged untill the end of full expression which is where semicolon in bar function call is located.

#include <iostream>
#include <string>

struct A
{
std::string foo() const{ return "aaa"; }
};

void bar(const char* c) {
std::cout << c;
}

int main()
{
A a;
bar(a.foo().c_str()); // Is this safe?
bar(a.foo().substr().c_str()); // or this
}

Answer Source

The temporary returned by foo() (and substr()) will continue to exist until the end of the bar call (after the chain of method calls), this is safe.

int main()
{
    A a;
    bar(a.foo().c_str()); 
    //temporary is destroyed here
    bar(a.foo().substr().c_str()); 
    // and here
}

Classical undefined behaviour case :

int main()
{
    A a;
    const char* charPtr = a.foo().c_str();
    printf("%s", charPtr);
}

Temporary std::string is created, a pointer to it's buffer is returned by c_str() and the temporary goes out of scope and is destroyed. charPtr now is a pointer pointing to an invalid location ( a dead std::string ).