以错误的方式初始化string_view的向量?

你好,

请告诉我为什么前 3 行不起作用而后 3 行起作用?

见: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';
}

最好的问候, 40tude

回答

在基于范围for循环的第一,w是一个复制的元件的W。在每次循环迭代后,w被销毁,留下悬空w.c_str()持有的指针std::string_view

您应该声明w为参考。例如

for (const std::string& w : W) Wbak1.push_back(w.c_str());


以上是以错误的方式初始化string_view的向量?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>