I use it when adding items to a hashtable that I've made. The hastable
requires a class that inherits MyNullClass. To add to the hastable I use
this:
MyHt->Put(key, new FooDataItem(ABC));
The last line calls new but doesnt assign it to any variable (it actually
doeswithin the hash table, but it doesnt appear to).
Yes, this is perfectly valid. The original post seems to be about "new
X();" without anything else. In general, it looks like a memory leak, but
as others point it need not be, as when you overload X:
perator new or
operator new, or in the constructor of X store the address of X somewhere.
And of course, the original code may have been a typo for placement new.
FooDataItem *lFDI = new FooDataItem(ABC);
MyHt->Put(key, lFDI);
Which is a bit messier in my opinion. I guess this comes from writing
programs in java.
Second way is safer in general as (but you also have to use smart pointers),
but either is fine for your specific example. In the expression Put(key(),
new Foo()) the compiler may evaluate the new Foo() first and suppose that
works, then it will evaluate key() and suppose that throws an exception,
then the new Foo is never deleted. So the safe way is
std::auto_ptr<FooDataItem> lFDI ( new FooDataItem(ABC) );
MyHt->Put(key, lFDI);
and the Put function receives an auto_ptr. The use of auto_ptr or any smart
pointer in the signature of Put implies that Put takes ownership of the
object, which is good documentation.