Search code examples
c++iteratorlifetimefunction-calltemporary-objects

Lifetime of temporary object: iterator to temporary vector in nested function call


Let's suppose that I have such classes:

struct QString {
    //return null terminated array
    std::vector<char> toLocal8Bit() const;
};

struct string_view {
    const char *data;
    size_t len;
    string_view(const char *str): data(str), len(std::strlen(str)) {}
};

and I have function with such signature:

void f(const string_view& str);

Is it valid code

QString str;
f(string_view(&*str.toLocal8Bit().begin()));

?

I mean when temporary std::vector will be destroyed?


Solution

  • The temporary is destroyed at the end of the full statement. So this is safe.