Constructor / destructor call mismatches

D

Dave Theese

Hello all,

Please see the two questions and output embedded in the program below.

Thank you!
Dave


#ifdef WIN32
#pragma warning(disable: 4786)
#endif

#include <iostream>
#include <map>

using namespace std;

template <int type_differentiator>
class foo
{
public:
explicit foo(int d): data(d)
{
cout << "foo<"
<< type_differentiator
<< ">() : "
<< data
<< endl;
}

~foo()
{
cout << "~foo<"
<< type_differentiator
<< ">(): "
<< data
<< endl;
}

bool operator<(const foo &lhs) const {return data < lhs.data;}

private:
int data;
};

int main()
{
map<foo<1>, foo<2> > bar;

cout << "Starting..." << endl;

// Question 1:
// How does the line below compile (when not commented out)? foo's
// constructor is explicit!
// bar.insert(make_pair(42, 17));

// Question 2:
// This line leads to an uneven number of constructor and destructor
calls.
// How is this possible?
bar.insert(
make_pair(
foo<1>(42),
foo<2>(17)
)
);

cout << "Exiting..." << endl;

return 0;
}

// As shown, the program above generates the output below when built with
// VC++ 6.0:
//
// Starting...
// foo<2>() : 17
// foo<1>() : 42
// ~foo<2>(): 17
// ~foo<1>(): 42
// ~foo<2>(): 17
// ~foo<1>(): 42
// ~foo<1>(): 42
// ~foo<2>(): 17
// Exiting...
// ~foo<2>(): 17
// ~foo<1>(): 42

// As shown, the program above generates the output below when built with
g++:
//
// Starting...
// foo<1>() : 42
// foo<2>() : 17
// ~foo<2>(): 17
// ~foo<1>(): 42
// ~foo<2>(): 17
// ~foo<1>(): 42
// ~foo<2>(): 17
// ~foo<1>(): 42
// Exiting...
// ~foo<2>(): 17
// ~foo<1>(): 42
 
W

WW

Dave said:
Hello all,

Please see the two questions and output embedded in the program below. [SNIP]
template <int type_differentiator>
class foo
{
public:
explicit foo(int d): data(d)
{
cout << "foo<"
<< type_differentiator
<< ">() : "
<< data
<< endl;
}

~foo()
{
cout << "~foo<"
<< type_differentiator
<< ">(): "
<< data
<< endl;
}

bool operator<(const foo &lhs) const {return data < lhs.data;}

private:
int data;
};

You are missing the copy constructor. Copies never show up as constructed
but they will show up as destructed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top