Search code examples
c++returndynamic-memory-allocation

General rule of thumb when to return Pointer vs return Object?


In many examples I see code like this:

SomeObject* constructObject() {
    SomeObject* obj = new SomeObject();
    return obj;
}

But what speaks against doing it this way:

SomeObject constructObject() {
    SomeObject obj = SomeObject();
    return obj;
}

?

What is the general rule of thumb of when to return an object vs when to return a pointer?

Edit: A little background:

I am rewriting a renderer that should be fast in both rendering itself aswell as providing the data. The previous programmer stored pointers in a vector. something like: vector<MeshModel*>. MeshModel itself doesnt have any inheritance. In my opinion it would be better to use vector<MeshModel> instead, since I wouldn't jump around randomly in the memory. Is my POV wrong?


Solution

  • std::vector<MeshModel> is more straightforward than std::vector<MeshModel*>.

    For use in a std::vector, one might be concerned about the cost of copy/move-construction during vector growth reallocations. If your SomeObject can be moved cheaply, then I would go for the by-value storage. Otherwise, there might be a performance tradeoff during creation of the vector. But that is most likely not worth caring about.

    Whether it brings speed while accessing the objects depends on too many other things (everything that affects caching, such as object size, access frequency/stride/predictability, target hardware... too much to list here) - profile if you care about performance. But there's no need to use indirection when you gain nothing from it.

    And as pointed out in the comments - stay away from owning raw pointers. std::unique_ptr<MeshModel> would work just fine in the code shown.