- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 152字
- 2021-06-10 18:27:59
Using Other Versions of the New Operator
Further, a custom type can define a placement operator new, which allows you to provide one or more parameters to the custom new function. The syntax of the placement new is to provide the placement fields through parentheses.
The C++ Standard Library version of the new operator provides a version that can take the constant std::nothrow as a placement field. This version will not throw an exception if the allocation fails, instead, the failure can only be assessed from the value of the returned pointer:
int *pi = new (std::nothrow) int [VERY_BIG_NUMBER];
if (nullptr == pi)
{
cout << "cannot allocate" << endl;
}
else
{
// use pointer
delete [] pi;
}
The parentheses before the type are used to pass placement fields. If you use parentheses after the type, these will give a value to initialize the object if the allocation is successful.