Denis Petronenko posted:
Hello,
Why do i can't write "new [1]" instead of "new" everywhere in
applications? So, i will not need to track where i must call delete and
where delete[]. Therefore, it will simplify coding.
Or application performance will be significantly reduced?
I actually used it once to *increase* performance one time:
#include <cstddef>
template<class T, std::size_t len>
struct DefInitArray {
T array[len];
DefInitArray() : array() {}
};
#include <cstring>
#include <ostream>
#include <cstdlib>
#include <iostream>
class StringStream {
protected:
enum { buflen = 1024U };
char *const pbuf;
char *pos;
public:
StringStream() :
/* LOOK AT THE FOLLOWING LINE */
pbuf( (new DefInitArray<char,buflen>[1])->array ),
pos( pbuf ) {}
StringStream(StringStream const &original) :
pbuf(new char[buflen]),
pos( pbuf + (original.pos - original.pbuf) )
{
std::memcpy(pbuf, original.pbuf, sizeof *pbuf * buflen);
}
StringStream &operator=(StringStream const &rhs)
{
std::memcpy(pbuf, rhs.pbuf, sizeof *pbuf * buflen);
pos = pbuf + (rhs.pos - rhs.pbuf);
return *this;
}
bool IsFull() const
{
return pos == pbuf + (buflen - 1);
}
StringStream &operator<<(char const c)
{
if( !IsFull() ) *pos++ = c;
return *this;
}
StringStream &operator<<(const char *p)
{
for( ; *p; ++p) *this << *p;
return *this;
}
void Print( std::ostream &out ) const
{
out << pbuf << '\n';
}
~StringStream()
{
delete [] pbuf;
/* Instead of this, I would have
needed something like.
normal_new ? delete pbuf : delete [] pbuf;
"normal_new" would have to be
a member object. Perhaps:
bool normal_new;
*/
}
};
--
Frederick Gotham