Unnamed Temporary C++ ObjectsThe main technique that makes StringPrintf possible is the use of unnamed temporary objects. Most C++ programmers use this technique very often, although most of the time, it is not explicit. For example, having a set of std::strings, the set function insert only accepts references to objects of type std::string. Nevertheless, you can correctly write:
<b>std::set<std::string> stringSet;</b> <b>stringSet.insert("ABC");</b>
This is possible because the compiler, when finding the C-string "ABC", looks for a way to convert the C-string to a const reference to a std::string object. It then finds that basic_string (the template base class of std::string) has a constructor basic_string(const char *s). The compiler uses this constructor to create an unnamed temporary object of std::string out of "ABC", and passes it to std::set.insert(). The line
is expanded to
A unnamed temporary std::string object is created and its reference is passed to the insert function. When the insert function returns, the temporary object is destroyed.