4

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.

Community
  • 1
  • 1

4 Answers4

6

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
}
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
2

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.

Signal Eleven
  • 231
  • 1
  • 6
1

You will indeed have to delete[] the returned pointer at some point: since every new[] must be balanced with a delete[]. That can be difficult to manage.

But why not maintain a std::string member in your class, and write

const std::string& getName() const
{
    return name; // name is the class member.
}

instead? Returning a const reference obviates a deep copy and also means the caller cannot modify the member.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

First of all I think you mean

strcpy( name, _name );
        ^^^^^^^^^^^

instead of

strcpy( _name, name );
        ^^^^^^^^^^^ 

The object of the class that returns the pointer to the dynamically allocated memory will not have access to this memory after returning the pointer.

So it is the client of the function who shall free the allocated memory.

As other already pointed it is better to use standard class std::string in such cases.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335