6

これは簡単な質問です:

new 演算子を使用すると、型 (void *) のポインターが返されますか? new/delete と 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; のようなコードは見たことがありません。

私は混乱しています。

編集

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))、 andが返されるはずです。throwing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);
(void *)

ありがとう

4

3 に答える 3

15

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
于 2013-05-02T18:40:20.027 に答える
0

void *代入時に上位の型にキャストする必要はありません。void *古い malloc シグネチャがchar *代わりに a を返したため、 が存在する前の古い c コードのみがキャストを必要とします。

于 2013-05-02T18:40:40.853 に答える