C
C++Liliput
I have a class of the type
class A
{
private:
std::string data;
.......
public:
const char* toString();
};
A::A(const char* s):data(s) {}
const char* A::toString() { return data.c_str()
I have the following scenario in the code:
A* pObj = new A("New");
const char* str = A -> toString();
............
............
delete pObj;
printf("The string representation of A is %s", str);
Now I know that the above code is probably wrong because I use the
char pointer returned by the c_str() function after the object
(containing a string member variable) has been deallocated. But I am
interested to know why. Is it because the c_str() returns the internal
char pointer of the string object? c_str() returns a null terminated
string which means that probably a copy of the internal char buffer
terminated with a null character is returned to the user. But if that
is the case, it should be the responsibility of the user to explicitly
deallocate the char pointer after it is not being used. But we don't
do it do we? So I am a bit confused about what exactly happens.
class A
{
private:
std::string data;
.......
public:
const char* toString();
};
A::A(const char* s):data(s) {}
const char* A::toString() { return data.c_str()
I have the following scenario in the code:
A* pObj = new A("New");
const char* str = A -> toString();
............
............
delete pObj;
printf("The string representation of A is %s", str);
Now I know that the above code is probably wrong because I use the
char pointer returned by the c_str() function after the object
(containing a string member variable) has been deallocated. But I am
interested to know why. Is it because the c_str() returns the internal
char pointer of the string object? c_str() returns a null terminated
string which means that probably a copy of the internal char buffer
terminated with a null character is returned to the user. But if that
is the case, it should be the responsibility of the user to explicitly
deallocate the char pointer after it is not being used. But we don't
do it do we? So I am a bit confused about what exactly happens.