I want to return a name, and while the main should be able to alter it (in main's scope), it should not change in the class.
If I do it like this:
char* get_name(){
char* name = new char[sizeof(_name)+1];
strcpy(_name,name);
return name;
}
do I have to delete[]
at some point? And when?
Edit: I don't believe it's the same problem as pointer to local variable since the problem here is how to delete it after i use it.
Well, that's the problem with manual memory management. Indeed, if you want to return a copy, then it would be the caller's responsibility to free the memory, which is extremely error prone. That's why C++ has std::string class which handles the memory;
std::string get_name() const //note the const on member function
{
return _name; //this will work even if _name is char*, btw
}
As others have said, using std::string is probably a better option. If you want to use a char* instead, I would suggest simply returning a const char*:
const char* get_name() {
return _name;
}
You will be returning a const reference, meaning that the calling code should not change it. The way you are doing it, you will indeed have to delete after every call to get_name(), which is not ideal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With