C++ Logo

std-discussion

Advanced search

Inconsistency in Examples

From: Daniel Markus <daniel_at_[hidden]>
Date: Thu, 23 Nov 2023 19:47:32 +0000
Hi!

I'm trying to learn about object lifetime and am reading the specification. When I was reading
§6.7.3/8 I realized that the example discards the return value from placement new, but that has
the [[nodiscard]] attribute (§17.6.3.4/1).
https://en.cppreference.com/w/cpp/memory/new/operator_new

There are a couple more examples also discarding: §6.7.3/(1, 6, 9, 10).

Following is a situation I have where I want to ensure the lifetime of the object.

struct S
{
    int i;
};

int main()
{
    S s = {};

    read_from_file(reinterpret_cast<std::byte*>(&s));
    new(&s) S; // Start lifetime (§6.7.2/13).
    // or
    std::start_lifetime_as<S>(&s); // C++23.

    s.i += s.i; // Use data with old reference (§6.7.3/8).

    return 0;
}

According to §6.7.3/5 and §6.7.3/8 I can read data directly into the struct s. The only thing left is
to start the lifetime of the new object.
My questions are:


  * If placement new is [[nodiscard]] I guess that I must use the returning pointer?
  * std::start_lifetime_as is not [[nodiscard]]. Does it mean that discarding its return value will work?


Best regards,
Daniel Markus


Received on 2023-11-23 19:47:35