2013-05-02 32 views
6

這是一個簡單的問題:在C++中新返回(void *)嗎?

是否使用new運算符返回類型爲(void *)的指針? 參考What is the difference between new/delete and malloc/free?答案 - 它說:new returns a fully typed pointer while malloc void *

但根據http://www.cplusplus.com/reference/new/operator%20new/

throwing (1)  
void* operator new (std::size_t size) throw (std::bad_alloc); 
nothrow (2) 
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) throw(); 
placement (3) 
void* operator new (std::size_t size, void* ptr) throw(); 

這意味着它返回一個類型(無效*)的指針,如果返回(無效*)我從來沒有見過一個代碼像MyClass * ptr =(MyClass *)new MyClass;

我有困惑。

編輯

按照http://www.cplusplus.com/reference/new/operator%20new/例如

std::cout << "1: "; 
    MyClass * p1 = new MyClass; 
     // allocates memory by calling: operator new (sizeof(MyClass)) 
     // and then constructs an object at the newly allocated space 

    std::cout << "2: "; 
    MyClass * p2 = new (std::nothrow) MyClass; 
     // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow) 
     // and then constructs an object at the newly allocated space 

所以MyClass * p1 = new MyClass電話operator new (sizeof(MyClass))以來throwing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);
它應該返回(void *)如果我理解正確的語法。

感謝

+2

[無恥的插件](http://stackoverflow.com/a/8962536/775806) – 2013-05-02 18:44:53

+1

[新表達的cppreference條目](http://en.cppreference.com/w/cpp/language/new) – dyp 2013-05-02 18:52:03

+0

@DyP好的..得到它..你想說什麼'new-expression(new int)使用分配函數(operator new)。分配函數只提供存儲,new-expression new type-id返回一個指向type-id(或者throws)的指針'..謝謝 – 2013-05-02 18:55:39

回答

14

你感到困惑operator new(它返回void*)和new操作(返回一個完全類型的指針)。

void* vptr = operator new(10); // allocates 10 bytes 
int* iptr = new int(10); // allocate 1 int, and initializes it to 10 
+1

標準把後者稱爲* new-expression *。 – LihO 2013-05-02 18:41:23

+0

思考它的一種方式是'new'表達式將內存轉換或「轉換」爲對象:void指針進入,對象指針出現。 – 2013-05-02 18:42:11

+0

john參考http://www.cplusplus.com/reference/new/operator%20new/'std :: cout <<「1:」; MyClass * p1 = new MyClass; //通過調用operator new(sizeof(MyClass))來分配內存//然後在新分配的空間上構造一個對象,它調用operator new(sizeof(MyClass))',所以基本上它應該返回' (void *)'根據您的參數 – 2013-05-02 18:43:13

0

void *並不需要進行分配時僅舊的C代碼之前的void *存在需要鑄造如舊的malloc簽名返回char *,而不是轉換爲較高的類型。

0

new將返回您正在創建實例的類型的指針。 operator new返回指向void的指針。 new相當常見,而operator new更獨特一些。