Dumb question, but whenever you call new, do you always have a pointer?
SomeClass *person = new SomeClass();
And is that because you need a poi
Yes. If you are asking why it doesn't return a reference instead, since references are nicer than pointers, the answer is historical heritage.
When C++ was in development, if the machine was unable to get memory for the object, a special pointer NULL
was returned. This is how it is done in C:
SomeClass *person;
person = (SomeClass*) malloc( sizeof( SomeClass ) );
if ( person == NULL ) fprintf( stderr, "no more people allowed!" );
In standard C++, errors are returned by exception instead:
try {
SomeClass *person = new SomeClass;
// do something
} catch ( std::bad_alloc ) {
std::cerr << "no more people!" << std::endl;
} catch ( ... ) {
// using exceptions allows for other errors
// from inside SomeClass::SomeClass too
}
You can still do it the old-fashioned way, though, with nothrow
:
SomeClass *person = new( std::nothrow ) SomeClass;
if ( person == NULL ) std::cerr << "no more people allowed!" << std::endl;
The upshot is, this is perfectly reasonable and good style:
SomeClass &person = * new SomeClass; // don't need no stinkin pointers!