new operator (STL Samples)

사용 하는 방법을 보여 줍니다. new 연산자 in <new>.

void *operator new(
   size_t n
)
void *operator new(
   size_t n,
   const nothrow&
)
void *operator new[](
   size_t n
);

설명

[!참고]

프로토타입에 클래스/매개 변수 이름은 헤더 파일에서 버전이 일치 하지 않습니다.일부 가독성을 높이기 위해 수정 되었습니다.

첫 번째 연산자가 메모리를 할당 하려고 시도 합니다 및 실패할 경우 예외를 throw 합니다.해당 두 번째 연산자 형식 nothrow의 두 번째 매개 변수를 허용 합니다.이 매개 변수 할당이 실패할 경우이 해야 NULL 반환 예외를 throw 함을 나타냅니다.해당 세 번째 연산자는 해당 형식의 배열에 대해 메모리를 할당 합니다 및 실패할 경우 예외를 throw 합니다.

예제

// newop.cpp
// compile with: /EHsc
//
// Functions:
//   void *operator new(size_t n)
//   void *operator new(size_t n, const nothrow&)
//   void *operator new[](size_t n);

#include <new>
#include <iostream>
using namespace std;

class BigClass {
public:
   BigClass() {};
   ~BigClass(){}

#ifdef _WIN64
      double BigArray[0x0fffffff];
#else
      double BigArray[0x0fffffff];
#endif
};

int main() {
   try {
      BigClass * p = new BigClass;
   }

   catch( bad_alloc a) {
      const char * temp = a.what();
      cout << temp << endl;
      cout << "Threw a bad_alloc exception" << endl;
   }

   BigClass * q = new(nothrow) BigClass;

   if ( q == NULL )
      cout << "Returned a NULL pointer" << endl;

   try {
      BigClass * r[3] = {new BigClass, new BigClass, new BigClass};
   }

   catch( bad_alloc a) {
      const char * temp = a.what();
      cout << temp << endl;
      cout << "Threw a bad_alloc exception" << endl;
   }
}

샘플 출력

bad allocation
Threw a bad_alloc exception
Returned a NULL pointer
bad allocation
Threw a bad_alloc exception

요구 사항

헤더: <new>

참고 항목

개념

표준 템플릿 라이브러리 샘플