1

Let's say I have a struct defined as so:

struct Barre {
        int startString;
        int endString;

        Barre() { startString = endString = -1; }
        Barre(int s, int e) : startString(s), endString(e) {}
        bool exists() { return startString > -1; }
        };

I will create an instance of this struct like this, for example:

Barre b = Barre(2, 4);

Let's say I insert this into a std::map<int, Barre> which is a member of a class, with a key of, for example, 3.

If I then create another Barre as above and overwrite the value of the map at key 3 with this new instance of the Barre struct, do I need to explicitly delete the old Barre object that I'm overwriting to prevent memory leaks? Or does it not persist once it is no longer stored in a map in this way?

Thanks for any help.

9
  • 1
    Also, as a rule of thumb for modern C++ (C++11 and later), you really shouldn't ever need to use new and especially not delete yourself, unless you are doing some pretty deep library development, or use some existing framework which requires you to use them for legacy reasons (for example with Qt you'll use new, but don't need delete, and C++11 doesn't yet have make_unique function). Instead, use smart pointers. Commented Mar 7, 2019 at 17:25
  • 3
    @JThistle "it's worth noting that I have searched for an answer to this and can't find anything." Well, this was the google query I used to find the duplicate questions: c++ when do i need delete site:stackoverflow.com Commented Mar 7, 2019 at 17:27
  • 1
    I used 'do I need to delete a struct' and variations on that, DuckDuckGo returned nothing helpful. Commented Mar 7, 2019 at 17:30
  • 2
    @JThistle The problem with your query might possibly have been that you searched for struct specifically, which is completely irrelevant for the question. A struct is just the same as a class with all members public as default. Nothing to do with dynamic memory management at all. Commented Mar 7, 2019 at 17:36
  • 2
    @πάνταῥεῖ When reading questions, it's good to keep in mind that things that are self-evident for someone who knows a language, necessarily aren't that for everybody, even experienced programmers. For example a C# developer (I don't know if OP is) entering C++ world might have a bit of WTF moment when they learn that struct and class are basically the same thing, and until that realization might have trouble formulating a suitable search engine query. Commented Mar 7, 2019 at 18:23

0