Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is constructing an object in an argument list and passing a pointer to internal data of the object to the function safe?

Is the C++ code below well-formed? Will the std::string get destroyed before or after the function finishes executing?

void my_function(const char*);

...

my_function(std::string("Something").c_str());

I know I could do my_function("Something"), but I am using std::string this way to illustrate my point.

like image 669
BlueCannonBall Avatar asked Nov 22 '25 02:11

BlueCannonBall


1 Answers

Will the std::string get destroyed before or after the function finishes executing?

Temporary objects are destroyed (with some exceptions, none relevant here) at the end of the full-expression in which they were materialized (e.g. typically the end of an expression statement).

The std::string object here is such a temporary materialized in the full-expression that spans the whole my_function(std::string("Something").c_str()); expression statement. So it is destroyed after my_function returns in your example.

like image 51
user17732522 Avatar answered Nov 24 '25 16:11

user17732522