使用c_str时"Use & to create a pointer to a member"
"Use & to create a pointer to a member" when using c_str
我正在尝试通过从字符串上施放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的工作方式不正确,要么做错了。用
推到ActionLogactionLog.push_back("something");
工作正常,但我提到的不是。我在做什么错?
编辑:我实际上在使用c_str()作为函数,我刚刚复制了它
实际上您要做的事情有几个问题。
- 首先,
c_str
是成员函数。您必须使用()
:str.c_str()
。
来调用它 -
c_str()
返回const char*
,因此您将无法将其存储在vector<char*>
中。这就是这样您不能通过以其预期的方式更改其内部设备来破坏std::string
。 - 您真的不应该存储
c_str()
的结果。它只有在您来自std::string
进行的一些非const
操作之前保持有效。IE。如果您更改std::string
的内容,请尝试使用vector
中的相应元素,您具有 undfined行为!从您制定示例的方式来看,string
的寿命看起来比vector
的寿命要短得多,因此vector
将指出甚至不存在的东西。
>
也许最好只使用std::vector<std::string>
。如果此之后您不需要原始的string
,则可以将其std::move
到vector
中,避免额外复制。
顺便说一句,请重新考虑您对通常被认为是不良做法的使用: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());
- C++线程"Call to non-static member function without an object argument"
- 当两个成员位于同一类中时出错"a nonstatic member reference must be relative to a specific object"
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- 'Pointer to member'错误C++
- 这是什么意思:"member reference type 'Human *' is a pointer; did you mean to use '->'?"
- 如果它被定义为 C++ 类中的成员函数,我得到了"non-standard syntax; use '&' to create a pointer to member"
- 如何解决访问不同功能的"nonstatic member reference must be relative to a specific object"
- 使用c_str时"Use & to create a pointer to a member"
- Visual Studio 2015:获取"non standard syntax, use '&' to create a pointer to member"错误
- 在这种情况下如何解决"Reference to non-static member function must be called"?
- 将"pointer-to-member"分配给自身
- 无法将"member pointer to derived class"转换为"member pointer to base class"
- 为什么一个文件中没有错误,另一个文件中没有错误 - "Non Static Member Reference mush be relative to specific object"
- "is not a member of"和"no matching function for call to"错误
- 'variable' 不是类型 'pointer to member function' 的有效模板参数
- "There is no "reference-to-member" type in C + +",std::bind 和 boost::bind 在同一条船上
- Visual Studio 2015 "non-standard syntax; use '&' to create a pointer to member"
- Visual Studio 2015 中的"non-standard syntax; use '&' to create a pointer to member"错误
- 你能"pointer to member"工会成员吗?
- Pointer-to-member-function error