Stack Temporaries
It is also possible to create un-named temporary values on the the stack using the class name and giving constructor parameters.
/* * You can create stack objects without creating a variable. */ #include <iostream> #include <string> using namespace std; class Fred { public: Fred(string s, int a) { m_val = a; m_lab = s; } Fred combine(Fred other) { // The expression on the return statement requires space for // a Fred object, which is allocated on the stack. The // space for the parameter other was also allocated there // when the the method was called. return Fred(m_lab+","+other.m_lab, m_val+other.m_val); // The value of the temporary fred object is copied into // the caller, then the space is freed when the method // returns. } string to_s() { return m_lab + ": " + to_string(m_val); } private: int m_val; string m_lab; }; int main() { // As before, these two object are allocated on the stack. Fred f1("skunk", 41); Fred f2("wombat", 33); // Here, two temporary objects are also allocated on the stack. cout << Fred("skunk", 41).to_s() << endl; cout << Fred("wombat", 33).to_s() << endl; // Some more here. cout << Fred("snake", 28).combine(Fred("goose", 9)).to_s() << endl; // The named objects f1 and f2 are cleared up here. The temporary // objects will be cleared here, or in an earlier place if the // compiler prefers. }