I’ve read that the default behavior in C++ is always copy. So I’m guessing that a get-function on a datamember also returns a copy of the datamember.
Normally this works fine but in this case one of my datamembers is a multimap. This is what I have right now:
class Track {
private:
multimap<long, Note> noteList;
public:
multimap<long ,Note> getNoteList()
{
return noteList;
}
}
But for some reason this doesn’t work. When I call getNoteList() I’m not getting any erros but the output of my program in the console stops (when I’m running my app). If I make noteList public everything works fine.
Is there any difference between regular types like int, char, float as compared to multimap? Any reason why this isn’t working hand how can I write a working getter function?
Returning a copy of a container may not be a very good idea. You will most likely end up copying way too much for nothing. If you don’t want the user to be able to change your existing container, you should return it by reference to
const.Now when a client of this class calls
getNodeList()is can accessnoteListmap directly, without the need to do expensive copies.If you also want to give clients the ability to directly modify that map, you can add an overload that returns a regular reference:
However, if you reach this point you should probably ask yourself why aren’t you just exposing
noteListdirectly.