小编use*_*835的帖子

push_back() a filesystem::path's .string().data() 的奇怪行为导致“vector<const char *>”

运行这个程序

#include <iostream>
#include <filesystem>
#include <vector>

using namespace std;
namespace fs = filesystem;

int main() {
    vector<fs::path> paths{"a.o", "b.o"};

    vector<const char *> argv{};
    for (auto &p : paths) {
        argv.push_back(p.string().data()); // line A
    }
    argv.push_back(paths[0].string().data());
    argv.push_back(paths[1].string().data());

    for (auto &s : argv) {
        cout << s << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

得到

b.o
b.o
a.o
b.o
Run Code Online (Sandbox Code Playgroud)

为什么 argv 的第一个元素不是“ao”?

我尝试在A线断,找出当“博”是的push_back()插入的argv,argv的的第一个元素改变从“AO”到“博”。

然后,当我将 A 行更改为

        argv.push_back(p.string().c_str()); // line A: .string().data() -> .string().c_str()
Run Code Online (Sandbox Code Playgroud)

结果一样。

当我将 A 行更改为

        argv.push_back(p.c_str()); // line …
Run Code Online (Sandbox Code Playgroud)

c++ string vector char std-filesystem

1
推荐指数
1
解决办法
79
查看次数

标签 统计

c++ ×1

char ×1

std-filesystem ×1

string ×1

vector ×1