Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is <new> only for Microsoft?

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
US
I'm wondering if anyone knows if the <new> header file is a standard header file or just for MSVC++?
Also, what's the point of including it? new is already a built in operator...
 
Thanks, but I still don't see why I would use <new>
I can overload new and delete without including <new>
 
Only <new> header declares std::bad_alloc exception (and std::size_t type - see C++ Standard).
Well, if you want to redefine new/delete looks like its pre-defined prototypes, you must include <new> header...
 
I've always used std::bad_alloc from <stdexcept>

But even if you are not redefining the new operator, I've seen examples in books that include <new> for programs as simple as this:
Code:
#include <new>
#include <iostream>
using std::cout;
using std::endl;

void main( void )
{
    char*  pszName = new char[40];
    cout << "Enter your name: ";
    cin >> pszName;
    cout << endl << "Hello " << pszName << endl;
    delete pszName;
}
Is there any point in using <new> in something like this?
 
One reason to include it is that it declares the [tt]nothrow[/tt] object.

Previous implementations of C++ would have [tt]new[/tt] return 0 when it failed to allocate memory. No one ever checked for this, though, and exceptions provided a better way to report the error, so that's what the new [tt]new[/tt] does in Standard C++.

However, if you want the old behavior, you can pass the (Standard) [tt]nothrow[/tt] object as an argument to [tt]new[/tt] and it will return 0 on failure and not throw an exception.


There's really no reason to include <new> in a simple program like that, at least not in Standard C++. It might be meaningful for particular compilers or libraries, though.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top