user1824034
user1824034

Reputation: 65

New array of pointers to class objects

I want the class OUT to hold an array of IN pointers. How many is unknown. This is what I have so far.

class OUT{
    class IN{/**/};
    IN** IN_handle;
    int m_size_in;
    OUT(int size_in):m_size_in(size_in){
        IN_handle = new *IN[size_in];
    }
    ~OUT(){
        for(int i=0; i<m_size_in; i++){
            delete IN_handle[i];
        }
        delete IN_handle;
    }
};

compiler says:

cannot convert 'int**' to 'OUT::IN**' in assignment

Upvotes: 0

Views: 115

Answers (2)

Garf365
Garf365

Reputation: 3707

Use std::vector and std::unique_ptr will save you a lot of work :

#include <vector>
#include <memory>

class OUT{
    public:
        class IN{/**/};
        std::vector<std::unique_ptr<IN>> IN_handle;

        void add(std::unique_ptr<IN> &&new_data)
        {
            IN_handle.push_back(std::move(new_data));
        }

        OUT()
        {
        }

        ~OUT()
        {
        }

        // Functions to manipulate IN_handle
};

and to use it:

OUT out;
out.add(std::make_unique<OUT::IN>());

From http://www.cplusplus.com/reference/vector/vector/:

Vectors are sequence containers representing arrays that can change in size.

Also std::unique_ptr take care of deleting allocated memory, so no need to be worry about that point ;)

Upvotes: 5

SergeyA
SergeyA

Reputation: 62573

Use a combination of std::vector with std::unique_ptr as your vector elements. Do not manually manage your pointers or dynamic arrays.

Upvotes: 1

Related Questions