STL source code analysis: code testing and understanding of temporary objects

Purpose: In-depth understanding of STL
Recently, I saw a very basic grammar, which is also a temporary object commonly used by ordinary people. It is a kind of unnamed object (copy operation will occur in any pass by value operation, so form a temporary object), you can see Liezi, shape(2,3) or int(8) both generate temporary objects. It is equivalent to calling the constructor. You can see it in the following example. For the object myprint(), it is not a function, but a temporary object. It can be used for parameters of functions. As follows, it is put into for_each to pass parameters.

#include<vector>
#include<algorithm>
#include<iostream>

template <typename T>
class myprint
{
    
    
	public:
		void operator()(const T& elem)
		{
    
    std::cout << elem <<' ';}
};

int main()
{
    
    
	int ia[6] = {
    
    0,1,2,3,4,5};
	std::vector<int> iv(ia, ia+6);
	std::for_each(iv.begin(), iv.end(), myprint<int>());
	std::cout<<std::endl;
}

As a result of the operation, I saw myprint(), which was passed in the parameter of iv, and a copy occurred.
insert image description here
For details, you can see the STL source code analysis book translated by Hou Jie.

Guess you like

Origin blog.csdn.net/weixin_43851636/article/details/122130417