8 ms·
> The pointer returned by new should belong to a resource handle (that can call delete). If the pointer returned by new is assigned to a plain/naked pointer, th
by klyrs 6y ago
> The pointer returned by new should belong to a resource handle (that can call delete). If the pointer returned by new is assigned to a plain/naked pointer, the object can be leaked
Unless I'm reading this wrong (and I'm seeking to be corrected here), it's still fine to use new/delete in certain contexts
struct bla {
int n;
int[] mem;
bla(int n) : n(n), mem(new int[n]{}) {}
~bla() { delete[] mem; }
/* forbid copies (for uniqueness) and moves (to keep this short) */
bla(bla &) = delete;
bla(bla &&) = delete;
bla &operator=(bla &&) = delete;
};
Edit to remove unnecessary null-checking
- f00zz 6y agoYou could just use std::vector<int> there
- klyrs 6y agoOf course you could. That wasn't my question -- my question was about the wording of the recommendation; "...should belong to a resource handle (that can call delete)"
- makecheck 6y agoNote above, the “delete” operator is safe to call on nullptr values, and it is also not necessary to set pointers to nullptr in destructors (since the object is going away anyway). The example above therefore could just say “delete [] mem;” in the destructor with nothing else. Yet this is also a good example of why you wouldn’t need “delete” or a destructor at all, if “mem” changes to std::unique_ptr<int[]> type. And even then, you should probably seriously consider std::vector or std::array before trying a unique_ptr array.
- zabzonk 6y agoIs: int[] mem; even legal C++?
- klyrs 6y agono, that was me being sloppy typing code on my phone
- lights0123 6y agoNot standard C++. If the [] was after the variable name, because it is the last member, most C++ compilers (GCC, Clang, and MSVC) have a non-standard extension: https://en.wikipedia.org/wiki/Flexible_array_member https://en.wikipedia.org/wiki/Flexible_array_member
- zabzonk 6y agoNot even non-standard C++ - my g++ compiler errors with: a.cpp:2:13: error: expected unqualified-id before '[' token
- lights0123 6y ago> If the [] was after the variable name
- detaro 6y agoshould. It's a guideline to avoid mistakes, it doesn't mean you can't do memory manually in C++, it's just recommended you avoid it unless you have a good reason.
- plorkyeran 6y agoThat struct should be just struct bla { int n; std::unique_ptr<int[]> mem; bla(int n) : n(n), mem(std::make_unique<int[]>(n)) { } }. There is no reason to use new/delete there.