np-hard
np-hard

Reputation: 5815

stl vectors add sequence

Iam using borland 2006 c++

class A
{
private:
    TObjectList* list;
    int myid;
public:
 __fastcall A(int);
 __fastcall ~A();
};

__fastcall A::A(int num)
{
    myid = num;
   list = new TObjectList();
}

__fastcall A::~A()
{
}

int main(int argc, char* argv[])
{
  myfunc();
  return 0;
}

void myfunc()
{
    vector<A> vec;
    vec.push_back(A(1));
}

when i add a new object A to the vector, it calls its destructor twice, and then once when vec goes out of scope , so in total 3 times.

I was thinking it should call once when object is added, and then once when vec goes out scope.

Upvotes: 1

Views: 253

Answers (3)

Loki Astari
Loki Astari

Reputation: 264381

Try this:

#include <iostream>
#include <vector>

class A
{
    private:
        public:
            A(int num)
            {
                std::cout << "Constructor(" << num << ")\n";
            }
            A(A const& copy)
            {
                std::cout << "Copy()\n";
            }
            A& operator=(A const& copy)
            {
                std::cout << "Assignment\n";
                return *this;
            }
            A::~A()
            {
                std::cout << "Destroyed\n";
            }
};

int main(int argc, char* argv[])
{
    std::vector<A> vec;
    vec.push_back(A(1));
}

The output on my machine is:

> ./a.exe
Constructor(1)
Copy()
Destroyed
Destroyed
>

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 791681

The expression A(1) is an r-value and constructs a new A value, the compiler may then copy this into a temporary object in order to bind to the const reference that push_back takes. This temporary that the reference is bound to is then copied into the storage managed by vector.

The compiler is allowed to elide temporary objects in many situations but it isn't required to do so.

Upvotes: 6

rlbond
rlbond

Reputation: 67749

When you hit your breakpoint, click the call stack tab at the bottom of your debugger. That way, you can find the context of each call.

Upvotes: 0

Related Questions