0

what is the best way to design a string class constructor? The following constructors definitely have problem: two pointers pointing one object, if one of them is destructed, the other will cause a fatal error. So, what is the best way to design a constructor for a string class?

class CMyString{ private: char *pData; public: CMyString(char *_p=NULL):pData(_p){ } CMyString(CMyString &_str):pData((_str.pData){ } } 
2
  • 1
    All of the string objects I have ever designed have MULTIPLE constructors that allow users to input differing data types into the string. Commented Feb 25, 2014 at 22:36
  • Since your class doesn't have a destructor, your statement is patently false. Commented Feb 25, 2014 at 22:42

2 Answers 2

2

For example you can define the class the following way.

class CMyString { private: char *pData; public: CMyString( const char *_p = NULL ) { if ( _p == NULL ) { pData = NULL; } else { pData = new char[ std::strlen( _p ) + 1 ]; std::strcpy( pData, _p ); } } CMyString( const CMyString &_str ) { if ( _str.pData == NULL ) { pData = NULL; } else { pData = new char[ std::strlen( _str.pData ) + 1 ]; std::strcpy( pData, _str.pData ); } } explicit operator bool () const { return ( pData != NULL ); } CMyString & operator =( const CMyString & ); // do not forget to define ~CMyString(); // do not forget to define }; 

Or you can define the copy constructor the following way

 CMyString( const CMyString &_str ) : CMyString( _str.pData ) { } 
Sign up to request clarification or add additional context in comments.

Comments

1

Allocate space and copy the characters over.

Also, I suggest not allowing pData to be null, as it complicates the logic. Instead, if no initial value is given, create an empty string.

Also, don't forget to be const-correct.

CMyString(const char *_p = "") { size_t len = strlen(_p); pData = new char[len+1]; strcpy(pData, _p); } CMyString(const CMyString& _str) { /* basically the same as above */ } 

7 Comments

CMyString myStr(0); will crash this
I also disagree with your statement about pData to be null. It is a very real possibility that a user could indeed pass in an un-initialized char * _p, and this case should be handled. It DOES complicated the logic, but it is NECESSARY complication, when coding SAFE code.
@Alex passing in an unterminated string could also crash it. So what? You just tell your users not to do it.
@trumpetlicks See my comment above.
I prefer programs that do not crash totally when smb forget to initialize char*. Passing 0 is happening quite often. Yes, std::string does not check and will crash also. But I would prefer SafeString which checks possible errors. Why you think MS implemented a set of *s safe functions? They could just tell their users not to use it wrong way. But the problem is that users _do.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.