简体   繁体   中英

What does “new Classname*[]” mean?

I have a class:

class WorkerThread
{
public:
    unsigned virtual run()
    {
        return 0;
    }
};

Defined in the header. Now in another class I create an object of this type:

WorkerThread **workerQueue;

Which is actually a pointer to pointer... OK, all good until now.
Now, how should I read this:

workerQueue = new WorkerThread*[maxThreads];

What is the meaning of the * after the ClassName ( WorkerThread ) and the array format?

It's an allocation of an array of WorkerThread pointers.

For instance:

size_t maxThreads = 3;
WorkerThread** workerQueue = new WorkerThread*[maxThreads];

workerQueue[0] is a WorkerThread* , as is WorkerThread[1] and WorkerThread[2] .

These pointers, currently have not been initialized.

Later you may see something like this:

for(size_t x = 0; x < maxThreads; ++x)
{
   workerQueue[x] = new WorkerThread(...);

   //beginthreadex_, CreateThread, something....
}

I will tell you, that all of these raw pointers are just memory leaks waiting to happen unless carefully handled. A preferred method would be to use a std::vector to some smart pointer of WorkerThread objects.

Maybe this will make it a little clearer to understand:

typedef WorkerThread* PointerToWorkerThread;

PointerToWorkerThread *workerQueue;

workerQueue = new PointerToWorkerThread[maxThreads];

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