Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass c_str return value of temporary object to printf

Tags:

c++

Is the following piece of code valid?

class A { string m_name;
public:
string getName() { return m_name; }
}

.....
printf("%s", object.getName().c_str())
......

where object.getName() returns a temporary string object.

like image 476
Prabhu Avatar asked Dec 28 '22 13:12

Prabhu


1 Answers

The temporary string will persist for until printf() completes so yes, it is safe and legal.

like image 72
sharptooth Avatar answered Jan 22 '23 00:01

sharptooth