In c++11, constructor can be forwarded to another constructor in the initialization list.
It is fine to call function in initialization list as in this question
Is it also fine to call function in the constructor delegate?
I tried code like this:
#include <iostream>
#include <string>
#include <yaml-cpp/yaml.h>
using namespace std;
YAML::Node ParseFromFile(const string& filepath) {
YAML::Node yaml;
try {
return YAML::LoadFile(filepath);
} catch(const YAML::BadFile& e) {
cout << "error";
}
}
class A {
public:
A(YAML::Node yaml) {
cout << "Got" << endl;
}
A(const string& filepath) : A(ParseFromFile(filepath)) {}
};
int main(int argc, char** argv) {
A a(string(argv[1]));
YAML::Node yaml = ParseFromFile(string(argv[1]));
A b(yaml);
return 0;
}
For the above code, just pass an empty file to it, it will only print one "Got" during the initialization of b.
=======================================================================
Replacing string(argv[1]) with argv[1] makes it work, any ideas why?