Open In App

Temporary Materialization in C++ 17

C++ is a popular programming language that is widely used in the development of system software, application software, game engines, and more. One of the most significant improvements in C++17 is the introduction of temporary materialization, a feature that helps reduce the complexity of code and improve performance. In this article, we will learn about this feature with the help of examples.

The emergence of temporary objects in C++17 is marked by the automatic creation of objects as needed by the language, without any explicit command to initiate their creation. Unlike the previous version, only when an expression resulted in a temporary object were such entities created; however, in C++17, their creation can occur in a broader range of circumstances.



Application of the temporary materialization

In C++, applications of temporary materialization are mentioned below:

Example 1: 






// C++ Program to demonstrate use of temporary
// materialization in C++17.
#include <iostream>
#include <string>
  
std::string foo() { return "Hello"; }
  
void bar(const std::string& str)
{
    std::cout << str << std::endl;
}
  
int main()
{
    bar(foo() + " world!");
    return 0;
}

Output
Hello world!

Explanation of the above program:

In this example, Upon calling the foo() function within the main() function, a fleeting std::string entity comprising the phrase ‘Hello’ is produced. By using the operator to combine this temporary std::string with the ‘world’, yet another momentary std::string entity is generated to accommodate the combined outcome. The const std::string parameter of the bar() function is supplied with an ephemeral std::string entity that is generated and sent as an input argument.

Example 2: 




// C++ Program to demonstrate use of use of the temporary
// materialization in C++17.
  
#include <iostream>
#include <string>
  
using namespace std;
  
string getName() { return "GeeksforGeeks"; }
  
int main()
{
    cout << getName() << endl;
  
    const string& name = getName();
    cout << name << endl;
  
    return 0;
}

Output
GeeksforGeeks
GeeksforGeeks

Explanation of the above program:

In the above example, the std::string object can be obtained through the usage of the getName() function. Specifically, by utilizing the line cout << getName() << endl; we are able to directly output the returned string value. Moreover, creating a constant reference to the getName() function’s return value can be done with the line const string, thus allowing for further manipulation.
Creating a constant reference name would have been impossible if the std::string object had been destroyed before initialization, which is only possible with the presence of Temporary Materialization in C++17.

Advantages of Temporary Materialization

The advantages of using Temporary Materialization are mentioned below:


Article Tags :
C++