[英]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.