Can links cause memory leak?

Consider the following C ++ code.

struct foo { std::string value; }

inline foo bar() { return { "42" }; }

Now imagine that I have a function that uses bar () as follows.

std::string my_func()
{
    const auto &x = bar();
    return x.value;
}

Does this memory leak. Since my_func only contains a reference to x? Or is x still cleared after my_func completes?

I know that this does not mean that links should be used. But I just realized that this compiles, and wondered what semantics are.

+4
source share
4 answers

But I just realized that this compiles.

The code provided should not be compiled as it is trying to assign a temporary reference to lvalue.

error: invalid initialization of non-constant reference of type 'foo & from rvalue of type' foo

,

std::string my_func()
{
    const auto &x = bar();
    return x.value;
}

, const.

+6

: .

: , . bar() n . , .

, , : , , , .

+3

No, the string is copied to the return value. The object referenced by x goes beyond the scope after the function.

+1
source

This is not a leak, your link simply points to memory that has been cleared by expanding the stack due to tempo. an object.

Accessing x will result in undefined behavior. Perhaps a violation of access rights.

+1
source

Source: https://habr.com/ru/post/1614659/


All Articles