I have multiple methods inside my class which need const char * so I convert string to const char * inside the constructor of my class and store it in a local variable with type const char *. The local variable is valid inside the constructor. However, it is empty when I call it on methods of the same class.
If I pass it using const references my problem is fixed but I expected my code works without using const references.
I followed How to convert a std::string to const char* or char*? for other methods to convert the string to const char *.I think the c_str() convert the string correctly.
I want to understand the root cause which cause my local variable to be empty. I prepared example codes for my problem.
Code with problem: #include #include
using namespace std;
class Config{
string strFileName_ = "/path/filename.ext";
public:
string getFileName() {return strFileName_;}
};
class Loader{
const char * className_;
public:
Loader(string name){
//className_ = name.c_str(); //same result with .data()
className_ = name.data();
cout << "[inside Loader constructor]className_ is:" << className_ << endl;
}
void loadFile(){
cout << "[inside loadFile] className_ is:" << className_ << endl;
}
};
int main(){
Config cfg;
Loader ld(cfg.getFileName());
ld.loadFile();
}
Code with string instead of const char * does not have this problem. As I explained, if I use const references, the problem is not there anymore. Code for references: #include #include
using namespace std;
class Config{
string strFileName_ = "/path/filename.ext";
public:
const string &getFileName() {return strFileName_;}
};
class Loader{
const char * className_;
public:
Loader(const string& name) {
className_ = name.c_str();
cout << "[inside Loader constructor]className_ is:" << className_ << endl;
}
void loadFile(){
cout << "[inside loadFile] className_ is:" << className_ << endl;
}
};
int main(){
Config cfg;
Loader ld(cfg.getFileName());
ld.loadFile();
}
Aucun commentaire:
Enregistrer un commentaire