So, I've always been a little fuzzy on C++ pointers vs. ... whatever the other one is called. Like,
Object* pointer = new Object();
vs.
Object notpointer();
I know that pointers are probably involved in the second one, but basically it's a not-pointer. (What's it actually called?)
Furthermore, I believe that for the first one, you have to call
delete pointer;
at some point once you're done with it, right? And the other one you don't need to worry about. I've read that the first is allocated on the heap, but the second is allocated on the stack, and goes away when the method returns.
However, what about when you're returning something (not a primitive) from a function?
A good example is written in Should I return std::strings?:
std::string linux_settings_provider::get_home_folder() {
return std::string(getenv("HOME"));
}
By what I previously wrote, the string is allocated on the stack, and should be freed when the function returns, right? Yet nobody said anything about that, so I assume it works fine. Why?
In general, what's the difference between
return new std::string("pointer");
and
return std::string("not-pointer");
?
Also, assuming both work, what are the pros and cons of the two?
When you return by pointer, you need to return a dynamically allocated object the way that you show (i.e. returning a pointer to a stack object results in undefined behavior if it is dereferenced later). This creates a potential for memory leaks, because, like you have noted, that object needs to be deleted explicitly.
Returning by value, on the other hand (i.e. the second snippet) results in copying the object that you return from the stack object into the object that receives the return value:
std::string res = get_home_folder(); // std::string gets copied into res
Compilers can optimize this to avoid copying through return value optimization.