#include <fstream.h>
#include <string.h>
#include <stdlib.h>
#include <strstrea.h>
class DeepString	{
public:
	DeepString(const char* nstr);
	DeepString(const DeepString& s);
	virtual ~DeepString();	//make virtual for possible derived
	int operator==(const DeepString& s) const;
	const char* data() const;
	operator const char*() const;
	operator int() const;
	const DeepString debug(ostream* out=0) const;
protected:
	int len;		//length of the string
	char* buf;	//buffer containing string
	};
typedef DeepString String;

const DeepString DeepString::debug(ostream* out) const	{
	strstream buffer;
	buffer << "len=" << dec << len
		 << ", buf=0x" << hex << (long)buf << ",";
	for(int i=0;i<len;i++)	{	buffer << (char)buf[i];	}
	buffer << ends;
	DeepString text(buffer.str());
	delete buffer.str();
	if (out)
		*out << text.data() << endl;
	return text;
}
main()	{
	ofstream out("test.dat");
	String s1("Hello World");
	cout << s1.debug().data() << endl;
	cout << s1.debug(&out).data() << endl;
}
/****** output *******************
cout:len=11, buf=0x367f01e2,Hello World
cout:len=11, buf=0x367f01e2,Hello World
test.dat:len=11, buf=0x367f01e2,Hello World
*********************************/
DeepString::DeepString(const DeepString& s)	{
	len = s.len;
	buf = new char[len];
	memcpy(buf,s.buf,len);
	}
DeepString::~DeepString()	{
//	cout << "DeepString<0x" <<
//		hex << (long)buf << ">::~DeepString()" << endl;
	delete [] buf;
}
int DeepString::operator==(const DeepString& s) const	{
	return (len == s.len) ? !memcmp(buf,s.buf,len) : 0;
}
DeepString::DeepString(const char* nstr)	{
	len = strlen(nstr);
	buf = new char[len];
	memcpy(buf,nstr,len);
	}
const char* DeepString::data() const	{
	if (buf[len] != 0)	{
		char* newBuf = new char[len+1];
		memcpy(newBuf,buf,len);
		newBuf[len]=0;
		delete [] buf;
		((DeepString*)this)->buf = newBuf;
	}
	return buf;
}
DeepString::operator const char*() const	{
	return data();
}
DeepString::operator int() const	{
	return atoi(data());
}


