user16255957
user16255957

Reputation:

C++ static vs global with pointers?

In C++11 I wrote (in global):

static MallocMetadata *dummy_block = &MallocMetadata{};

And I got a warning that I am taking address of temporary.

  1. Why is this a warning? isn't static living until the end of my main.cpp file?

  2. When I changed it to:

    static MallocMetadata dummy_block = MallocMetadata{}, *last_free_block = &dummy_block;
    

I didn't get a warning regarding last_free_block why is that?

Upvotes: 0

Views: 64

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

The compiler does not complain about dummy_block being a temporary, but MallocMetadata{} is a temporary. In this line:

static MallocMetadata *dummy_block = &MallocMetadata{};

Lifetime of that temporary last till ;. You can store a pointer to it, but immediately after the initialization the pointer becomes useless.

PS: Your 2. seems to be ok-ish, but it is unclear why you insist on a pointer when you need to store the object somewhere anyhow:

static MallocMetadata dummy_block;

And anywhere you are using dummy_block use &dummy_block instead.

Upvotes: 2

Related Questions