我的類中有多個需要const char *的方法,所以我將字符串轉換爲const char *,並將其存儲在類型爲local的變量中const char *。局部變量在構造函數中有效。但是,當我在同一個類的方法上調用它時,它是空的。轉換std :: string爲const char *和函數調用
如果我使用const引用傳遞它,我的問題已修復,但我期望我的代碼在不使用const引用的情況下工作。
我跟着How to convert a std::string to const char* or char*?爲其他方法將字符串轉換爲const char *。我認爲c_str()正確地轉換字符串。
我想了解導致我的本地變量爲空的根本原因。 我爲我的問題準備了示例代碼。
代碼問題:
#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();
}
代碼字符串,而不是爲const char *不存在這個問題。正如我所解釋的,如果我使用const引用,問題就不存在了。 代碼引用:
#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'?使用'const char *'有什麼好處? –
您的意思是「它是空的」是什麼意思?它是'NULL'還是'nullptr'?你在使用什麼平臺/ C++編譯器/運行時?根據[C++標準(C++ 14)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf),'name.data()'應該返回一個「分配副本」:*指向分配副本 的第一個元素,該元素的第一個元素由'str.data()'的原始值 指向的數組*由於它是分配副本, 'd認爲無論新的obect的構造函數完成後源'string'對象發生了什麼,它都應該是有效的。 –
我需要const char *因爲我使用需要這種格式的PETSc庫。但是,我的問題與PETSc庫無關,而且一般。 –