使用c_str时"Use & to create a pointer to a member"

"Use & to create a pointer to a member" when using c_str

本文关键字:to member pointer create Use str 使用      更新时间:2023-10-16

我正在尝试通过从字符串上施放char*的向量向向量添加一个char*。这是我正在使用的代码:

vector<char*> actionLog;
// lots of code
int value = ...
// lots of code
string str = "string";
cout << str << value << endl;
str += std::to_string(player->scrap);
actionLog.push_back(str.c_str());

问题在于,我为push_back行创建指定的"使用&amp;为成员创建指针"错误。str.c_str应该返回一个char*,这是ActionLog使用的类型。我要么对C_ST的工作方式不正确,要么做错了。用

推到ActionLog
actionLog.push_back("something");

工作正常,但我提到的不是。我在做什么错?

编辑:我实际上在使用c_str()作为函数,我刚刚复制了它

实际上您要做的事情有几个问题。

  1. 首先,c_str是成员函数。您必须使用()str.c_str()
  2. 来调用它
  3. c_str()返回const char*,因此您将无法将其存储在vector<char*>中。这就是这样您不能通过以其预期的方式更改其内部设备来破坏std::string
  4. 您真的不应该存储c_str()的结果。它只有在您来自std::string进行的一些非const操作之前保持有效。IE。如果您更改std::string的内容,请尝试使用vector中的相应元素,您具有 undfined行为!从您制定示例的方式来看,string的寿命看起来比vector的寿命要短得多,因此vector将指出甚至不存在的东西。
  5. >

也许最好只使用std::vector<std::string>。如果此之后您不需要原始的string,则可以将其std::movevector中,避免额外复制。


顺便说一句,请重新考虑您对通常被认为是不良做法的使用:using namespace std;endl(这些是解释的链接)。后者有点有争议,但至少了解原因并做出明智的决定。

std::basic_string::c_str()成员函数,而不是数据成员 - 您需要使用()进行调用。

正确的代码是:

actionLog.push_back(str.c_str());

请注意,std::basic_string::c_str()将指针返回到const char-您的actionLog向量应为类型std::vector<const char*>

vittorio的答案告诉您您在详细信息中做错了什么。但是我认为您做错了什么是真正使用vector<char*>而不是vector<string>

使用指针的向量,您必须担心基础字符串的寿命,因为它们会无效,从您的下方变化,等等。actionLog的名称表明事物是长寿的,您用来添加的代码表明str是用于构建日志字符串的本地助手变量,而没有其他。 str的时刻不超出范围,矢量包含一个悬空的指针。

将矢量更改为 vector<string>,做一个actionLog.push_back(str),不必担心生命或无效。

您忘记了(),C_ST是一种方法,而不是数据成员。只需写actionLog.push_back(str.c_str());

相关文章: