By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,276 Members | 1,406 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,276 IT Pros & Developers. It's quick & easy.

question on construction of pair in <utility>

P: n/a
consider the program:

#include <cstdlib>
#include <iostream>
#include <utility>

using namespace std;

class Test
{
public:
Test(int arg = 0);
Test(const Test &rhs);
Test &operator=(const Test &rhs);

private:
int val;
};

Test::Test(int arg) : val(arg)
{
cout << "Test one arg ctor" << endl;
}

Test::Test(const Test &rhs) : val(rhs.val)
{
cout << "Test copy ctor" << endl;
}

Test &Test::operator=(const Test &rhs)
{
cout << "operator= called" << endl;

if (this != &rhs)
val = rhs.val;

return *this;
}

int main()
{
Test one(1);

cout << endl << "pair ctor" << endl;
pair<int, Test>(1, one);

cout << endl << "make_pair" << endl;
make_pair(2, one);

return EXIT_SUCCESS;
}

I compiled the above program with
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp

The output of the above program is:

Test one arg ctor

pair ctor
Test copy ctor

make_pair
Test copy ctor
Test copy ctor
Here make_pair calls one extra Test copy ctor compared to the
pair<int, Test>(1, one).

Will this be the case always ? If so, can it be concluded that
pair<T1, T2>(const T1 &, const T2 &) should be preferred to
make_pair() ?

Kindly clarify.

Thanks
V.Subramanian
Aug 20 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
su**************@yahoo.com, India wrote:
[.. defining class Test ..]
Here make_pair calls one extra Test copy ctor compared to the
pair<int, Test>(1, one).

Will this be the case always ? If so, can it be concluded that
pair<T1, T2>(const T1 &, const T2 &) should be preferred to
make_pair() ?
There is no way to predict when the compiler will decide to forgo
creation of a temporary (that's what you're seeing here). It is allowed
to construct the object directly if it can, but it is also allowed to
actually use as any number of intermediate objects (temporaries) as the
semantics require. How 'make_pair' constructs its return value depends
on the implementation and on the way you use that function.

So, in short "no, it will not necessarily always be the case".

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 20 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.