Assuming we have some class defined which has a pointer to a char*, something like this
class MyClass
{
public:
static MyClass* create(const char* str = "Some str")
{
MyClass* ptr = new MyClass();
ptr->mStr = str; // the string is not deep copied.
return ptr; //EDIT
}
const char* getStr()
{
return mStr;
}
private:
const char* mStr;
}
Somewere in the code the object is created:
MyClass* cls = MyClass::create("Some str2");
Somewere else in the code after other functions have executed i have this:
const char* str = cls->getStr();
// str == "Some str2"
At this point the str has a valid pointer, either the default "Some str", or whatever the caller passed in function create.
Can anyone explain me why the memory of str was not altered? From what I know, the string was created on the stack and the memory was freed when the execution left the function, although the function is static, could this be the reason?
MyClassclass object, but this one holds a pointer to a constant memory. (And thus you should notdelete mStr, by the way, if you wanted to do that...)