2013-05-02 24 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(); 

によると、それは(void *型)を返す場合、私は、コードを見たことがない、(void *型)タイプのポインタを返すことを意味しますMyClass * ptr =(MyClass *)new MyClassのように。

私は混乱しています。

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 

http://www.cplusplus.com/reference/new/operator%20new/例1として

EDIT

のでMyClass * p1 = new MyClassoperator new (sizeof(MyClass))を呼び出し、私が正しく構文を理解すればthrowing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);
ので、それは(void *)を返す必要があります。

おかげ

+2

[恥知らずのプラグ](http://stackoverflow.com/a/8962536/775806) –

+1

[新しい表現のためのcppreferenceエントリ](http://en.cppreference.com/w/cpp/language/new) – dyp

+0

@DyP Ok ..それは..何を言っているのですか?new-expression(new int)は、割り当て関数(operator new)を使います。割り当て関数は記憶域を提供するだけで、新しい式の新しい型IDは型ID(またはスロー)へのポインタを返します。ありがとう –

答えて

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

+0

「new」式は、メモリをオブジェクトに「変換」または「キャスト」します。voidポインタが入り、オブジェクトポインタが出てきます。 –

+0

john http://www.cplusplus.com/reference/new/operator%20new/ 'std :: cout <<" 1: "; MyClass * p1 = new MyClass; //演算子new(sizeof(MyClass))を呼び出してメモリを割り当てます。 //新しく割り当てられた領域にオブジェクトを作成します。 'operator new(sizeof(MyClass))'を呼び出します。 (void *) 'あなたの議論の通り –

0

void *void *の存在が古いmallocの署名が代わりにchar *を返すようなキャストが必要です前から割り当てのみ古いCコードの間に高い型にキャストする必要はありません。

0

newは、あなたがインスタンスを作成しているタイプのポインタを返します。 operator new voidへのポインタを返します。 newはかなり一般的ですが、operator newはもう少しユニークです。

関連する問題