运行这个程序
#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)