1

C++17 introduced the new attribute [[nodiscard]] in p0189r1. When a function is decorated with this attribute, the return type must not be discarded. If it is discarded, a warning is emitted.

Example:

[[nodiscard]] void* allocateMemory();

void doWork() {
    allocateMemory(); // Warning is emitted, because the value is not stored in a variable and thus is discarded
}

This seems to be a good addition for any function that returns anything that later must be freed/destroyed/deleted/... again. However, the standard did not change the definition of the global new operator to make use of this new annotation. Is there any good reason for this?

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
Brotcrunsher
  • 1,964
  • 10
  • 32
  • Backwards compatibility pole vaults to mind. – stark Oct 15 '17 at 02:05
  • 2
    @stark It would be backwards compatible though. It just emits a warning, not an error. – Brotcrunsher Oct 15 '17 at 02:06
  • @Brotcrunsher: Lots of us compile with `-Werror`, meaning warnings are errors too. – John Zwinck Oct 15 '17 at 02:14
  • @JohnZwinck In that case this special warning could be discarded with another compile flag (forgot which one but I think there is one). Even with backwards compatability in mind, isn't code which does not safe the return value of new just plain wrong? Maybe the question could be converted to "When does it make sense to discard the return value of new?". – Brotcrunsher Oct 15 '17 at 02:20
  • 6
    https://issues.isocpp.org/show_bug.cgi?id=271. It simply came in too late for C++17. – T.C. Oct 15 '17 at 02:24
  • 1
    @T.C. you can create a self-deleting object with operator new... – Massa Oct 17 '17 at 17:19
  • @Massa How? Afaik you can't. RAII does not count because RAII also calls delete. – Brotcrunsher Oct 17 '17 at 18:51
  • 1
    @Brotcrunsher you can `new` a suicidal object (that even puts itself in some container somewhere); see https://stackoverflow.com/questions/3150942/is-delete-this-allowed – Massa Oct 20 '17 at 16:26
  • 1
    @T.C. You should probably expand that into a full answer. – Daniel H Oct 23 '17 at 18:49
  • @Brotcrunsher Qt does this all the time, with parent/child objects. – Oktalist Feb 07 '19 at 12:37

1 Answers1

0

The paper P0600R0 proposes applying [[nodiscard]] to Library functions and it enumerates the global operator new as one of the functions it must be applied to.
As mentioned by TC in the comments, this could not make it to the C++17 standard itself. A bug titled: "[[nodiscard]] in the Library" was also filed. It was decided to adopt this into a later draft.

The standard draft n4713 incorporates this change.

6.6.4.4 Dynamic storage duration [basic.stc.dynamic]
...
2. ... The following allocation and deallocation functions are implicitly declared in global scope in each translation unit of a program.

[[nodiscard]] void* operator new(std::size_t);
[[nodiscard]] void* operator new(std::size_t, std::align_val_t);
P.W
  • 26,289
  • 6
  • 39
  • 76