简体   繁体   English

new(3)是什么意思?

[英]What does new(3) mean?

SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);

What's the meaning of the new operator here? 这里的new运算符是什么意思?

What's the meaning of the number 3 after the new operator? new运算符后面的数字3是什么意思?

This code comes from LLVM's codebase . 此代码来自LLVM的代码库 There's a custom operator new in scope and it is being used to placement-new initialize the objects (cfr. placement syntax ) 范围内有一个operator new的自定义operator new ,它用于新放置对象的初始化(cfr。 放置语法

void *User::operator new(size_t Size, unsigned Us) {
  return allocateFixedOperandUser(Size, Us, 0);
}

Here's a toy example: 这是一个玩具示例:

class SelectInst
{
public:
  int x;
};

void *operator new(size_t Size, unsigned Us) {
                                ^^^^^^^^^^^ 3 is passed here
                   ^^^^^^^^^^^ allocation size requested

  return ... // Allocates enough space for Size and for Us uses
}

SelectInst *Create() {
  return new(3) SelectInst();
}

int main()
{
  auto ptr = Create();
  return 0;
}

Live Example 现场例子

Specifically that code is being used to adjust the allocated space to fit additional data. 具体来说,该代码用于调整分配的空间以适合其他数据。

Suppose SelectInst provides a user-defined placement operator new , which takes an int as user-defined argument; 假设SelectInst提供了一个用户定义的放置运算符new ,它使用一个int作为用户定义的参数; the invocation syntax means use that user-defined placement operator new for memory allocation. 调用语法意味着使用operator new用户定义的放置operator new进行内存分配。 eg 例如

class SelectInst {
public:
    static void* operator new (std::size_t count, int args) {
    //                                            ~~~~~~~~
        ...
    }
};

SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
//                   ~~~

You probably have custom operator new in SelectInst or at global scope (similarly to placement new ): 您可能在SelectInst或全局范围内具有了new的自定义运算符(类似于放置new ):

struct SelectInst
{
    SelectInst(/*...*/);
    // ...

    static void* operator new(std::size_t sz, int custom);
    static void operator delete(void* ptr, int custom); // new counter part
};

or 要么

void* operator new(std::size_t sz, int custom);
void operator delete(void* ptr, int custom); // new counter part

See last part of operator_new 参见operator_new的最后一部分

On the doc , it says that this is the amount of memory to request in bytes. doc上 ,它表示这是要请求的内存量(以字节为单位)。 (If it wasn't overloaded) Here's this is a request of 3 *8 = 24 bit to store the objet in memory. (如果未过载)这是3 * 8 = 24位的请求,用于将对象存储在内存中。 Think of this at some sort of remnant of malloc. 考虑一下malloc的某种残余。

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

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