As title says, i know that new throws an exception which can be caught, but what exactly happens to the pointer? it turns NULL? I checked some answers on SO but none explained it.
Check example below, the pointer keeps on the heap? please give full info on this pattern
#include <windows.h>
#include <cstdlib>
#include <iostream>
using namespace std;
enum eReadMode
{
// READ_ONLY,
READ_WRITE,
// CREATE_FILE,
// CREATE_WRITE_FILE,
};
class CFileStatic
{
private:
FILE *m_File;
public:
CFileStatic( LPCTSTR szFileName, eReadMode eMode );
virtual ~CFileStatic() {};
bool IsValidFile() const { return( m_File != NULL ); };
void PrintFile( unsigned int uLine = 0 );
};
CFileStatic::CFileStatic( LPCTSTR szFileName, eReadMode eMode )
{
if( szFileName )
{
if( eMode == READ_WRITE )
m_File = fopen( szFileName, "r+" );
else
printf( "Valid usage of: READ_WRITE only" );
}
else
m_File = NULL;
}
void CFileStatic::PrintFile( unsigned int uLine )
{
static unsigned uFindNumber;
if( uLine == 0 )
{
char szBuffer[1024];
while( fgets( szBuffer, 1024, m_File ) )
{
std::cout << szBuffer;
}
}
else
{
char szBuffer[1024];
while( fgets( szBuffer, 1024, m_File ) )
{
uFindNumber++;
if( uFindNumber == uLine )
{
std::cout << szBuffer;
}
}
}
}
int main( int argc, char *argv[] )
{
//if new fails, what 'pFile' turns out to be? and do I need to delete
//it later?
CFileStatic *pFile = new CFileStatic( "Console.h", READ_WRITE );
if( pFile->IsValidFile() )
{
pFile->PrintFile(2);
}
CFileStatic *pConsoleCpp = new CFileStatic( "Console.cpp", READ_WRITE );
if( pConsoleCpp->IsValidFile() )
{
pConsoleCpp->PrintFile();
}
system("pause>nul");
return EXIT_SUCCESS;
}
When an exception is thrown out of a function the function does not complete and does not return anything, at the same time control flow jumps to the exception handler and even if the function returned, the assignment to the receiving pointer would not be executed.
The same goes for the throwing version of
new, if it throws, then the pointer would maintain the same value it had before the expression, which might be NULL or any other value.On the other hand, if you use
new (std::nothrow) X;then the call tonewwill not throw, and failure will be indicated by a NULL value being returned (and assumingly assigned to a pointer)