basic question for vector

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

    #1

    basic question for vector

    I have a vector which I save the pointer.

    function()
    {
    std::vector <CMyData*> vpMyData;
    vpMyData.push_b ack(new CMyData(0));
    vpMyData.push_b ack(new CMyData(1));
    vpMyData.push_b ack(new CMyData(2));
    vpMyData.push_b ack(new CMyData(3));

    //??????????????? Required ???????????//
    delete vpMyData[0];
    delete vpMyData[1];
    delete vpMyData[2];
    delete vpMyData[3];

    }

    Should I delete all memory before I leave the function?

  • Rolf Magnus

    #2
    Re: basic question for vector

    kathy wrote:
    [color=blue]
    > I have a vector which I save the pointer.
    >
    > function()[/color]

    Your function is missing a return type.
    [color=blue]
    > {
    > std::vector <CMyData*> vpMyData;
    > vpMyData.push_b ack(new CMyData(0));
    > vpMyData.push_b ack(new CMyData(1));
    > vpMyData.push_b ack(new CMyData(2));
    > vpMyData.push_b ack(new CMyData(3));
    >
    > //??????????????? Required ???????????//
    > delete vpMyData[0];
    > delete vpMyData[1];
    > delete vpMyData[2];
    > delete vpMyData[3];
    >
    > }
    >
    > Should I delete all memory before I leave the function?[/color]

    Yes. Otherwise you have a memory leak. Btw: You can also simply store the
    objects instead of pointers. Then the memory is released automatically.

    Comment

    • Mateusz Łoskot

      #3
      Re: basic question for vector

      kathy wrote:[color=blue]
      > I have a vector which I save the pointer.
      >
      > function()
      > {
      > std::vector <CMyData*> vpMyData;
      > vpMyData.push_b ack(new CMyData(0));
      > vpMyData.push_b ack(new CMyData(1));
      > vpMyData.push_b ack(new CMyData(2));
      > vpMyData.push_b ack(new CMyData(3));
      >
      > //??????????????? Required ???????????//
      > delete vpMyData[0];
      > delete vpMyData[1];
      > delete vpMyData[2];
      > delete vpMyData[3];
      >
      > }
      >
      > Should I delete all memory before I leave the function?
      >[/color]

      Every object allocated dynamically by new operator must be deallocated
      by delete operator. std::vector does not have any knowledge to
      distinguish when you store objects and when you store pointers-to-objects.

      Cheers
      --
      Mateusz Łoskot

      Comment

      • hytecredneck@gmail.com

        #4
        Re: basic question for vector

        alternately you could create a new class that inherits from vector, and
        provides a destructor that cleans up all the pointers. or don't use
        pointers.

        Comment

        • Luke Meyers

          #5
          Re: basic question for vector

          kathy wrote:[color=blue]
          > I have a vector which I save the pointer.
          >
          > function()
          > {
          > std::vector <CMyData*> vpMyData;
          > vpMyData.push_b ack(new CMyData(0));
          > vpMyData.push_b ack(new CMyData(1));
          > vpMyData.push_b ack(new CMyData(2));
          > vpMyData.push_b ack(new CMyData(3));
          >
          > //??????????????? Required ???????????//
          > delete vpMyData[0];
          > delete vpMyData[1];
          > delete vpMyData[2];
          > delete vpMyData[3];
          >
          > }
          >
          > Should I delete all memory before I leave the function?[/color]

          Well, you should delete it when you're done using the vector. A couple
          of suggestions to make this easier on yourself:

          1. Use a "smart pointer" which will handle the deletion for you. There
          are many flavors of smart pointers, which provide varying semantics
          depending on your needs. There's std::auto_ptr, boost::shared_p tr,
          boost::scoped_p tr, and boost::intrusiv e_ptr, for starters.

          2. If you're dead set on using raw pointers, at least use std::for_each
          when you want to do the deletions.

          3. Read about the paradigm "Resource Acquisition Is Initialization, " or
          "RAII."

          Luke

          Comment

          • Mike Wahler

            #6
            Re: basic question for vector


            <hytecredneck@g mail.com> wrote in message
            news:1136656854 .799580.146590@ g43g2000cwa.goo glegroups.com.. .[color=blue]
            > alternately you could create a new class that inherits from vector,[/color]

            This can lead to trouble, since type 'std::vector's
            destructor is not virtual.

            -Mike


            Comment

            • Rolf Magnus

              #7
              Re: basic question for vector

              Mike Wahler wrote:
              [color=blue][color=green]
              >> alternately you could create a new class that inherits from vector,[/color]
              >
              > This can lead to trouble, since type 'std::vector's
              > destructor is not virtual.[/color]

              This would only be a problem if a vector gets dynamically allocated, which
              is usually not done.

              Comment

              • ma740988

                #8
                Re: basic question for vector

                || 2. If you're dead set on using raw pointers, at least use
                std::for_each
                || when you want to do the deletions.
                At least use std::for_each!! Could you elaborate on this? Interesting

                Comment

                • Shezan Baig

                  #9
                  Re: basic question for vector

                  Rolf Magnus wrote:[color=blue]
                  > This would only be a problem if a vector gets dynamically allocated, which
                  > is usually not done.[/color]


                  Not necessarily:


                  union {
                  char buffer[sizeof(MyDerive dVector)];
                  void *align;
                  };

                  new (buffer) MyDerivedVector (...);
                  std::vector<T> *vec = reinterpret_cas t<MyDerivedVect or*>(buffer);
                  ....
                  ....
                  vec->~std::vector<T >(); // BAD


                  This is not dynamically *allocated*, it is dynamically *constructed*
                  :)

                  Just playing,
                  -shez-

                  Comment

                  • Axter

                    #10
                    Re: basic question for vector

                    ma740988 wrote:[color=blue]
                    > || 2. If you're dead set on using raw pointers, at least use
                    > std::for_each
                    > || when you want to do the deletions.
                    > At least use std::for_each!! Could you elaborate on this? Interesting[/color]

                    I believe he/she is referring to code similar to the following:
                    for_each(vpMyCl ass.begin(), vpMyClass.end() , DeleteObject()) ;

                    Where DeleteObject() is a functor.

                    However, I recommend using the following method instead, which (IMHO)
                    is cleaner:
                    class DeleteObject
                    {
                    public:
                    template<typena me T>
                    bool operator()(T& ptr)
                    {
                    delete &*ptr;
                    ptr = NULL;
                    return true;
                    }


                    };


                    Example usage:
                    vpMyClass.erase (remove_if(vpMy Class.begin(),
                    vpMyClass.end() ,DeleteObject() ), vpMyClass.end() );


                    The above DeleteObject will work with any object type

                    Comment

                    • Axter

                      #11
                      Re: basic question for vector

                      Luke Meyers wrote:[color=blue]
                      > kathy wrote:[color=green]
                      > > I have a vector which I save the pointer.
                      > >
                      > > function()
                      > > {
                      > > std::vector <CMyData*> vpMyData;
                      > > vpMyData.push_b ack(new CMyData(0));
                      > > vpMyData.push_b ack(new CMyData(1));
                      > > vpMyData.push_b ack(new CMyData(2));
                      > > vpMyData.push_b ack(new CMyData(3));
                      > >
                      > > //??????????????? Required ???????????//
                      > > delete vpMyData[0];
                      > > delete vpMyData[1];
                      > > delete vpMyData[2];
                      > > delete vpMyData[3];
                      > >
                      > > }
                      > >
                      > > Should I delete all memory before I leave the function?[/color]
                      >
                      > Well, you should delete it when you're done using the vector. A couple
                      > of suggestions to make this easier on yourself:
                      >
                      > 1. Use a "smart pointer" which will handle the deletion for you. There
                      > are many flavors of smart pointers, which provide varying semantics
                      > depending on your needs. There's std::auto_ptr, boost::shared_p tr,
                      > boost::scoped_p tr, and boost::intrusiv e_ptr, for starters.
                      >[/color]

                      auto_ptr can not be used with an STL container.
                      A compliant C++ compiler will fail to compile when attempting to
                      push_back on a container of auto_ptr's.

                      When creating a container of smart pointers, I recommend using a clone
                      smart pointer like cow_ptr or copy_ptr.



                      You can also consider using boost::ptr_vect or, which is a container of
                      clonable pointers.

                      Comment

                      • Old Wolf

                        #12
                        Re: basic question for vector

                        Axter wrote:
                        [color=blue]
                        > auto_ptr can not be used with an STL container.
                        > A compliant C++ compiler will fail to compile when attempting to
                        > push_back on a container of auto_ptr's.[/color]

                        I'm not so sure that this is a requirement, I thought it just
                        causes undefined behaviour (because auto_ptr does not
                        satisfy the requirements that the container type be Copyable).

                        Comment

                        • ma740988

                          #13
                          Re: basic question for vector


                          || The above DeleteObject will work with any object type
                          The underlying tenet then surrounds the use of a function object - or
                          something similar, not necessarily the use of a specific algorithm?

                          Comment

                          • Bo Persson

                            #14
                            Re: basic question for vector


                            "Old Wolf" <oldwolf@inspir e.net.nz> skrev i meddelandet
                            news:1136932941 .676203.50440@g 49g2000cwa.goog legroups.com...[color=blue]
                            > Axter wrote:
                            >[color=green]
                            >> auto_ptr can not be used with an STL container.
                            >> A compliant C++ compiler will fail to compile when attempting to
                            >> push_back on a container of auto_ptr's.[/color]
                            >
                            > I'm not so sure that this is a requirement, I thought it just
                            > causes undefined behaviour (because auto_ptr does not
                            > satisfy the requirements that the container type be Copyable).[/color]


                            You are both right. :-)

                            There is no explicit requirement for a compiler diagnostic, but the
                            standards committee has worked hard to define auto_ptr such that it is
                            highly *probable* to fail to compile as a component of a standard
                            container.

                            Especially its copy constructor and assignment operator taking a
                            non-const reference, make almost all compílers complain.


                            Bo Persson


                            Comment

                            • Axter

                              #15
                              Re: basic question for vector

                              Old Wolf wrote:[color=blue]
                              > Axter wrote:
                              >[color=green]
                              > > auto_ptr can not be used with an STL container.
                              > > A compliant C++ compiler will fail to compile when attempting to
                              > > push_back on a container of auto_ptr's.[/color]
                              >
                              > I'm not so sure that this is a requirement, I thought it just
                              > causes undefined behaviour (because auto_ptr does not
                              > satisfy the requirements that the container type be Copyable).[/color]

                              IAW C++ standard, declaring a container of auto_ptr results in
                              undefined behavior.
                              However, IAW C++ standard adding anything to a container of auto_ptr
                              results in a compile error. That's why I specifically referred to
                              getting a compile error when calling push_back.
                              The standard does not explicitly states that calling push_back resutls
                              in a compile error.
                              However, if a compiler applies the STL container and auto_ptr
                              implementation described in the standard, then it would have no choice
                              but to produce a compile error when calling push_back.

                              The following is from an older thread which gives a good description
                              why a C++ compliant compiler must give a compile error when calling
                              push_back.
                              *************** *************** *************** *************** *************** *************** ****
                              STL Containers store contained types by value (value
                              semantics). It is therefore required that the contained type should at
                              least have a copy constructor and (or) assignment operator - depending
                              on operations performed and the container type. If you takes as
                              example, one of the sequence containers (vector or list), then you
                              would notice (in the std) that for modifiers type T is passed as (const

                              T&).

                              example (from std):
                              void push_back( const T& x ); //or..
                              iterator insert( iterator pos, const T& x );


                              It should therefore be impossible to use std::auto_ptr<X > as type T, as

                              auto_ptr's copy constructor (and assignment op) requires (X& x) as
                              argument. It does not meet the copy-constructable requirements of the
                              container.
                              *************** *************** *************** *************** *************** *************** ****

                              Comment

                              Working...