more about vectors

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Lasse Skyum

    more about vectors

    Suppose i have a std::vector containing 2 elements. If I delete the first
    element, the second element will be copied to the first position. A little
    test showed that the deleted element was indeed destructed, but there was
    never executed a copy-constructor for moving the remaining element??


    class CMyClassA
    {
    public:
    CMyClassA(){pri ntf("+");} // construct

    CMyClassA(const CMyClassA &a){printf("c") ;} // copy construct

    virtual ~CMyClassA(){pr intf("-");} // destruct
    };

    void test(){
    CMyClassA q;
    vector<CMyClass A> a;
    a.push_back(q); // Insert two elements
    a.push_back(q);
    printf("|");
    a.erase(a.begin (),a.begin()+1) ; // Remove the first element
    printf("|");
    }

    This test prints "+ccc-|-|--" , but I would have expected there to be a 'c'
    somewhere between the two | |.

    Can anyone explain this?

    --
    Lasse


  • Max M

    #2
    Re: more about vectors

    "Lasse Skyum" <no spam> wrote:[color=blue]
    >
    > Suppose i have a std::vector containing 2 elements. If I delete the first
    > element, the second element will be copied to the first position. A little
    > test showed that the deleted element was indeed destructed, but there was
    > never executed a copy-constructor for moving the remaining element??[/color]

    How can you know the destructed object is indeed the erased element?
    I guess the values are shifted through assignment, and then the last
    element is destructed. (Redefine assignment to keep track of when it gets
    called, and print the object's address to know who gets really destructed.)

    Max

    Comment

    • Lasse Skyum

      #3
      Re: more about vectors



      [color=blue]
      > How can you know the destructed object is indeed the erased element?[/color]

      Hmmm... guess that was kind of an assumption...
      [color=blue]
      > I guess the values are shifted through assignment, and then the last
      > element is destructed. (Redefine assignment to keep track of when it gets
      > called, and print the object's address to know who gets really[/color]
      destructed.)

      Yes, you are right! The element is simply assigned, not destructed and
      copy-constructed again as I thought it would be.

      --
      Lasse


      Comment

      Working...