memC
memC

Reputation: 1025

deleting an array that stores pointers to some objects

I am storing pointers to elements of a vec_A in an array A* a_ptrs[3] . Assume that vec_A will not be resized. So, a_ptrs[i] will point to the correct element.

My question is:

Suppose A* a_ptrs[3] is declared in a class B. Since it is not created using 'new' I am guessing I don't need to delete it in the destructor. Am I right??

class A {
      public:                       
             int getNumber();            
             A(int val);
             ~A(){};
      private:
              int num;
};    
A::A(int val){
         num = val;
         };             
int A::getNumber(){
    return num;
};

 int main(){  
    int i  =0;
    int num;    
    std::vector<A> vec_A;
    for ( i = 0; i < 10; i++){
        vec_A.push_back(A(i));
        }

    A* a_ptrs[3];        
    a_ptrs[0] = &vec_A[0];        
    a_ptrs[1] = &vec_A[3];        
    a_ptrs[2] = &vec_A[5];

    for (i = 0; i<3; i++){
        std::cout<<"\n: a_ptrs[i].getNumber() = "<<a_ptrs[i]->getNumber();
    }        
    std::cout << "\nPress RETURN to continue...";
    std::cin.get();    
    return 0;
}

Upvotes: 0

Views: 86

Answers (3)

Ashish
Ashish

Reputation: 8529

Correct, since there is no dynamic memory allocation in the program.

My Suggestion is to use vector.reserve() function to reserve the size of the vector which will improve program performance.

Basically when you add an element to CArray(MFC) or std::vector it reallocates necessary memory and copies the elements so it will lead to memory fragmentation and will degrade program speed.

Upvotes: 0

Dmitry Yudakov
Dmitry Yudakov

Reputation: 15734

Yes, delete is used only for variables allocated with new.

Upvotes: 2

Robben_Ford_Fan_boy
Robben_Ford_Fan_boy

Reputation: 8738

Yep, thats correct. You don't need to use delete. The only issue is if the vector is resized e.g. by calling push_back etc - but you called that out in your post.

Upvotes: 2

Related Questions