Constructor / destructor call mismatches

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Theese

    Constructor / destructor call mismatches


    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_differenti ator>
    class foo
    {
    public:
    explicit foo(int d): data(d)
    {
    cout << "foo<"
    << type_differenti ator
    << ">() : "
    << data
    << endl;
    }

    ~foo()
    {
    cout << "~foo<"
    << type_differenti ator
    << ">(): "
    << 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



  • WW

    #2
    Re: Constructor / destructor call mismatches

    Dave Theese wrote:[color=blue]
    > Hello all,
    >
    > Please see the two questions and output embedded in the program below.[/color]
    [SNIP][color=blue]
    > template <int type_differenti ator>
    > class foo
    > {
    > public:
    > explicit foo(int d): data(d)
    > {
    > cout << "foo<"
    > << type_differenti ator
    > << ">() : "
    > << data
    > << endl;
    > }
    >
    > ~foo()
    > {
    > cout << "~foo<"
    > << type_differenti ator
    > << ">(): "
    > << data
    > << endl;
    > }
    >
    > bool operator<(const foo &lhs) const {return data < lhs.data;}
    >
    > private:
    > int data;
    > };[/color]

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

    --
    WW aka Attila


    Comment

    Working...