Re: return string - no double allocation
Yes, you can do reference counting on the pointer. A simple implementation
would use boost::shared_ptr, but it does have some overhead. A smarter
implementation would use boost::intrusive_ptr, or equivalent code.
I never used any of the above techniques. <ash on my head> Can you briefly
explain how I would implement that in my class:
static char* NO_DATA=""; // like NULL, but c_str() can return this
class DGStr
{
public:
DGStr() :m_len(0),m_dat(NO_DATA) {}
DGStr(const DGStr& s):m_len(0),m_dat(NO_DATA) {*this=s;}
DGStr& operator=(const DGStr& s)
{
Alloc(s.m_len);
m_len=s.m_len;
strcpy(m_dat, s.m_dat);
}
~DGStr() {if(m_dat!=NO_DATA) delete[] m_dat;}
const char* c_str()const {return m_dat;}
private:
// very simple non optimized code
void Alloc(int n)
{
char* pD=new char[n+1];
if(m_dat != NO_DATA)
{
memcpy(pD, m_dat, m_len+1);
delete[] m_dat;
}
m_dat = pD;
}
// data
char* m_dat;
int m_len;
}