【发布时间】:2020-06-18 16:01:11
【问题描述】:
我是 C++ 编程新手(主要使用 Java),C++ 类、成员字符串和字符串转换为 const char* 和 c_str() 的这种行为让我感到困惑。
我有一个header,一个class和main函数如下:
sample.h
class Sample
{
private:
int id;
std::string text;
public:
Sample(int id);
void setId(int id);
int getId();
void setText(std::string txt);
std::string getText();
void loadText();
~Sample();
}
sample.cpp
Sample::Sample(int id)
{
this->id = id;
}
void Sample::setId(int id)
{
this->id = id;
}
int Sample::getId()
{
return this->id;
}
void Sample::setText(std::string txt)
{
this->text = txt;
}
std::string Sample::getText()
{
return this->text;
}
void Sample::loadText()
{
this->text = "Loaded";
}
Sample::~Sample()
{
std::cout << "Destructor is called." << std::endl;
}
main.cpp
void main()
{
int id = 1;
Sample* sample = new Sample(id);
// Case: 1 - If I do this, it does not work. Prints gibberish.
sample->loadText();
const char* text = sample->getText().c_str();
std::cout << text << std::endl;
// Case: 2 - Otherwise, this works.
sample->loadText();
std::cout << sample->getText().c_str() << std::endl;
// Case: 3 - Or, this works
sample->loadText();
std::string txtCpy = sample->getText();
const char* text = textCpy.c_str();
std::cout << text << std::endl;
}
所有三个案例一次完成一个。
案例 3 确实满足我的用例(即将字符串传递给需要 const char* 的 C 库。但是,我无法弄清楚案例:1 和案例:3 之间的区别?如果我们是按值返回字符串,如何将其复制到中间变量使其在运行时符合要求?
【问题讨论】:
-
这是未定义的行为。见这里:stackoverflow.com/questions/35980664/…
标签: c++ string pointers memory c-strings