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 <iostream> #include <string> 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 <iostream> #include <string> 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(); }
std::string? What is the benefit to usingconst char *?NULLornullptr? What platform/ C++ compiler/run-time are you using? According to the C++ Standard (C++14),name.data()should return an "allocated copy": points at the first element of an allocated copy of the array whose first element is pointed at by the original value ofstr.data(). Since it's an allocated copy, I'd think it should be valid no matter what happens to the sourcestringobject after your new obect's constructor is complete.