Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why std::make_pair is getting input by value instead of by const reference?

Tags:

c++

Referring to this web site http://www.cplusplus.com/reference/std/utility/make_pair/

The std::make_pair has this signature (and possible implementation):

template <class T1,class T2>
pair<T1,T2> make_pair (T1 x, T2 y)
{
    return ( pair<T1,T2>(x,y) );
}

I am wondering why std::make_pair has input parameter by value and not by const references?

Is there any particular reason for this?

like image 259
Alessandro Teruzzi Avatar asked Mar 16 '12 11:03

Alessandro Teruzzi


People also ask

What is std :: Make_pair?

std::make_pairCreates a std::pair object, deducing the target type from the types of arguments.

Why do we pass or return variables by const * or const&?

We pass by const reference to avoid making a copy of the object. When you pass a const reference, you pass a pointer (references are pointers with extra sugar to make them taste less bitter).

How does Make_pair work in C++?

The make_pair() function, which comes under the Standard Template Library of C++, is mainly used to construct a pair object with two elements. In other words, it is a function that creates a value pair without writing the types explicitly.

What are the differences between passing a parameter by reference and by constant reference?

The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in. Because the reference is a const reference the function body cannot directly change the value of that object.


1 Answers

It originally was taking the parameters by const reference, but that introduced some unexpected problems. It was changed to pass by value after a defect report:

http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#181

It is expected that the compiler will inline the function and be able to optimize away the parameter passing most of the time.

like image 113
Bo Persson Avatar answered Sep 28 '22 08:09

Bo Persson