0

Bonjour,

Could please tell me why the first 3 lines do not work while the last 3 ones work?

See : https://gcc.godbolt.org/z/qozEsc

#include <vector>
#include <string_view>
#include <iostream>

int main(){

    const std::vector<std::string> W = {"aaa", "bbbb", "ccccc"};
    
    std::vector<std::string_view> Wbak1;
    for (std::string w : W) Wbak1.push_back(w.c_str());
    for(auto w:Wbak1) std::cout << w << '\n';

    std::vector<std::string_view> Wbak2;
    for (auto i = 0U; i < W.size(); ++i) Wbak2.push_back(W[i].c_str());
    for(auto w:Wbak2) std::cout << w << '\n';
}

Best regards, 40tude

1 Answer 1

7

In the 1st range-based for loop, w is a copy of the element of W. After each loop iteration, w is destroyed, leaving the w.c_str() pointer held by std::string_view dangling.

You should declare w as a reference. e.g.

for (const std::string& w : W) Wbak1.push_back(w.c_str());
Sign up to request clarification or add additional context in comments.

2 Comments

@40tude You're welcome. :) This is the note of std::string_view that we have to pay attention to the lifetime of the pointed-to character array.
@40tude • these things can be subtle. Even the C++ experts I work with get tripped up from time to time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.