简体   繁体   English

“新类名* []”是什么意思?

[英]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? ClassName( WorkerThread )和数组格式WorkerThread*是什么意思?

It's an allocation of an array of WorkerThread pointers. 它是对WorkerThread指针数组的分配。

For instance: 例如:

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

workerQueue[0] is a WorkerThread* , as is WorkerThread[1] and WorkerThread[2] . workerQueue[0]WorkerThread*WorkerThread[1]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. 首选方法是使用std::vector指向WorkerThread对象的某些智能指针。

Maybe this will make it a little clearer to understand: 也许这会使您更清楚地了解:

typedef WorkerThread* PointerToWorkerThread;

PointerToWorkerThread *workerQueue;

workerQueue = new PointerToWorkerThread[maxThreads];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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