Running this program
#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;
}
gets
b.o
b.o
a.o
b.o
Why isn't the first element of argv "a.o"?
I try to break at line A, finding out that when "b.o" is push_back() into argv, the first element of argv changed from "a.o" to "b.o".
Then, when I change line A to
argv.push_back(p.string().c_str()); // line A: .string().data() -> .string().c_str()
Same results.
When I change line A to
argv.push_back(p.c_str()); // line A: .string().data() -> .c_str()
Suddenly I get what expected:
a.o
b.o
a.o
b.o
Can someone explain the weird behavior and the difference between .string().data() and .c_str()?