简体   繁体   中英

Pointer to array object in c++

I'm sort of new to C++ (coming from Java) and I want to declare an array object in a class, but it requires an integer value in its template parameters. I figured I'd have to make a pointer to an array class, but it does not work..

I want to make something like:

class foo{
    private:
        array *myArray;
    public:
        foo(int size){
            //This line may be terribly wrong, but you see what I mean
            myArray = new array<int,5>(); 
        }
        ~foo(){
            free(myArray);
        }
}

Though, the correct initialization of an array object is:

array<int,5>

but this way does not let me choose length in runtime.

I highly recommend that you pick up a good introductory C++ book , and forget about Java. Seriously, thinking in Java is counterproductive when learning C++. They may have similar syntax but they have very, very different semantics.

The issues you're having is related to fundamental concepts of the language. You have to learn the fundamentals from a good C++ introductory book before moving on.


std::array (if that's what you're using) is not the correct class to use for this particular application, because of the fact that you want to choose the length at runtime. The size of the std::array is fixed at compile-time.

You should use std::vector instead, which allows you to specify (and change) the size at runtime.

The standard containers such as std::vector manages the memory for you; you don't need to new or delete the standard containers. The standard containers exist because so you don't have to manually deal with memory yourself.

#include <vector>

class foo
{ 
private: 
    std::vector<int> myArray; 
public: 
    foo(int size) : myArray(size) // Sets the size of the array
    {
    } 

    ~foo()
    { 
        // You don't need to delete anything; the vector takes care of itself.
    } 
};

Notice that I didn't use pointers, new , delete , malloc() , or free() anywhere here. You often don't need pointers for many, many cases in C++ . Contrary to popular belief, there's very little manual memory management that you actually have to do when using modern C++ techniques. In fact, if you're using delete or free() in your C++ code, you're probably doing it very wrong.

I would like to stress again the importance of a good introductory C++ book in assisting you with the language. Any good intro C++ book will cover std::vector and how to use it to your advantage. Other resources such as a std::vector reference can also be of assistance. Familiarize yourself with them.

I believe what you're looking for is a vector class. It's a contiguous array-like storage structure (nice stackoverflow question ), and a C++ alternative to C arrays.

You can do it with a pointer, but since vector is dynamically growing in size, it's not that important.

Here's an example from your example:

#include <vector>

class foo{
    private:
        std::vector<int> *vecPointer;
    public:
        foo(int size){
            vecPointer = new std::vector<int>(size, 0);
                // 0 as default value, can be omitted
        }
        ~foo(){
            delete vecPointer;
        }
}

An alternative, if you just want to reserve memory, but don't actually have elements at the time of class initialization, would be to just reserve the memory instead of filling it with concrete int values. In that case, the constructor would look something like:

foo::foo(int size){
     vecPointer = new std::vector<int>();
     vecPointer->reserve(size);
}

The destructor does not change, and inside the class foo , you can add object up to the reserved size with vecPointer->push_back(5) , and you can add more objects than that in exactly the same way (only after that the vector size and the memory it takes will grow).

Also, do you really want to use pointers? You don't have to, you could just have a normal vector:

#include <vector>

class foo{
    private:
        std::vector<int> vec;
    public:
        foo(int size){
            vec.resize(size, 0); // it's initialized as empty here
            // alternative, with reserve:
            // vec.reserve(size);
        }
        ~foo(){
            // no deletion needed like this
        }
}

This way, everything is taken care of and you don't have to remember to delete.

foo(int size) {
    myArray = new int[size];  // Allocate n ints and save ptr in a.
    for (int i=0; i<size; i++) {
        myArray[i] = 0;    // Initialize all elements to zero. 
}

Other answers have answered the question nicely (you don't need to manage memory), but suppose you want to manage memory yourself (using new operator)-

then use a Unique pointer ( smart pointers ) to point to the array.

#include <memory>

class foo{
    private:
        std::unique_ptr<int> myArray;
    public:
        foo(int size){
            myArray.reset(new int[5]); 
        }
        ~foo(){
        }
}

You don't need to release memory here (just like vectors).

But remember the best solution is to use vectors (as pointed out), but since the question title read "Pointer to array", I have added a way to smartly point to array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM