Implementing c_str()

Hello, I try to write my own c_str() function of my own MyString Class.

I wrote some code but not sure about its quality:

1
2
3
4
5
6
7
8
  const char* c_str() const//available only after MyString was created 
	{ 
		MyString *ptr = const_cast<MyString*>(this);
		ptr->data_array_c_str = new char[data_length + 1];
		copy(data_array_c_str, data_length, 0);
		data_array_c_str[data_length] = '\0';
		return data_array_c_str;
	}
If it is c_str() a la the standard C++ library, the complexity should be O(1)

To achieve this, you would need to maintain space for one extra character at the end which has a value of zero (which is not a logical part of the sequence of characters that the string holds).

The code as written would leak memory, and the call to copy doesn't seem to be right.
Last edited on
what does the class itself use to store the chars? is it a c-string inside?
hello jonnin,
the class itself stores the chars in an array terminated with null. It seems that my c_str() func just only should return the pointer of the array.

This is only part of the code to see how the chars are stored:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyString
{
public:
MyString(const char *cp):data(new char[std::strlen(cp)+1]), data_length(std::strlen(cp))
	{
		std::copy(cp, cp + std::strlen(cp), stdext::checked_array_iterator<char*>(data, data_length));
		data[data_length] = '\0';
	}

private:
	size_t data_length;
	char* data;
	
};
correct just return the pointer. However I highly recommend you make an actual copy:

char* copyof = new char[strlen(data)];
strcpy(copyof, data);
return copyof;

then the user cannot change data via the pointer, which is 'bad'.
however while you class can destroy copyof pointer memory on destructor, it cant ensure the user does not have a pointer to that memory that will go bad... and that is OK but it needs to be understood and documented who owns the copyof memory and who is responsible for destroying it (the class or the user).


> It seems that my c_str() func just only should return the pointer of the array.

Yes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class MyString
{
public:

    MyString(): data_length(0), date( new char[1]{} ) {} // default constructor

    MyString(const char *cp) : data_length( std::strlen(cp) ), data(new char[std::strlen(cp)+1])
    {
        std::strcpy( data, cp ) ; // copies a null terminated string      
    }

    const char* c_str() const { return data ; }

private:
	size_t data_length;
	char* data;
};


This will engender undefined behaviour:
1
2
3
char* copyof = new char[strlen(data)];
strcpy(copyof, data);
return copyof;


Don't get into this kind of mess; return type of c_str() const should be const char*
Last edited on
I am apparently having an extra bad day @ c++.
My apologies!
Topic archived. No new replies allowed.