C ++:仅针对两种相同情况之一的迭代器错误
C++: Iterator error only for one of two identical cases
我使用迭代器以完全相同的方式(几乎)循环遍历相同的字符串对象,而第二个一直返回错误。我觉得我真的很傻,我是不是漏掉了什么?
#include <string>
#include <vector>
using namespace std;
struct Sentence
{
string text;
Sentence(const string& text)
: text{text}
{
for (string::const_iterator it = text.cbegin(); it != text.cend(); ++it)
{
// Actions: WORKS FINE:
}
}
string str() const
{
for (string::const_iterator it = text.cbegin(); it != text.cend(); ++it)
{
// Actions: RETURNS ERROR: Process finished with exit code 132 (interrupted by signal 4: SIGILL)
}
}
};
int main()
{
vector<Sentence> vec;
vec.push_back(Sentence{""});
vec[0].str();
return 0;
}
string str() const
正如您在这里看到的,您的 str()
被声明为返回 std::string
,但实际代码没有 return
任何东西。
这称为“未定义的行为”,从现在开始您不能期待任何有意义的结果。
您将需要修复此 str()
方法,以便它们正确地声明为返回 void
,或者实际上 returns 返回 std::string
。
所有现代 C++ 编译器都会发出有关此常见错误的警告或诊断消息。如果您的编译器在您编译代码时产生了警告消息,这将是一个不忽略来自编译器的 any 类型消息的示例。如果您没有从编译器收到任何消息,请检查其设置和命令行选项,并打开所有警告消息,或者升级您的编译器。
我使用迭代器以完全相同的方式(几乎)循环遍历相同的字符串对象,而第二个一直返回错误。我觉得我真的很傻,我是不是漏掉了什么?
#include <string>
#include <vector>
using namespace std;
struct Sentence
{
string text;
Sentence(const string& text)
: text{text}
{
for (string::const_iterator it = text.cbegin(); it != text.cend(); ++it)
{
// Actions: WORKS FINE:
}
}
string str() const
{
for (string::const_iterator it = text.cbegin(); it != text.cend(); ++it)
{
// Actions: RETURNS ERROR: Process finished with exit code 132 (interrupted by signal 4: SIGILL)
}
}
};
int main()
{
vector<Sentence> vec;
vec.push_back(Sentence{""});
vec[0].str();
return 0;
}
string str() const
正如您在这里看到的,您的 str()
被声明为返回 std::string
,但实际代码没有 return
任何东西。
这称为“未定义的行为”,从现在开始您不能期待任何有意义的结果。
您将需要修复此 str()
方法,以便它们正确地声明为返回 void
,或者实际上 returns 返回 std::string
。
所有现代 C++ 编译器都会发出有关此常见错误的警告或诊断消息。如果您的编译器在您编译代码时产生了警告消息,这将是一个不忽略来自编译器的 any 类型消息的示例。如果您没有从编译器收到任何消息,请检查其设置和命令行选项,并打开所有警告消息,或者升级您的编译器。