簡體   English   中英

new(3)是什么意思?

[英]What does new(3) mean?

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

這里的new運算符是什么意思?

new運算符后面的數字3是什么意思?

此代碼來自LLVM的代碼庫 范圍內有一個operator new的自定義operator new ,它用於新放置對象的初始化(cfr。 放置語法

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

這是一個玩具示例:

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;
}

現場例子

具體來說,該代碼用於調整分配的空間以適合其他數據。

假設SelectInst提供了一個用戶定義的放置運算符new ,它使用一個int作為用戶定義的參數; 調用語法意味着使用operator new用戶定義的放置operator new進行內存分配。 例如

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

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

您可能在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
};

要么

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

參見operator_new的最后一部分

doc上 ,它表示這是要請求的內存量(以字節為單位)。 (如果未過載)這是3 * 8 = 24位的請求,用於將對象存儲在內存中。 考慮一下malloc的某種殘余。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM