Michel H
Michel H

Reputation: 363

C++: Iterator error only for one of two identical cases

I'm looping over (almost) the same string object in exactly the same way, using iterators, and the second one keeps returning an error. I feel really stupid, am I missing something?

#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;
}

Upvotes: 1

Views: 99

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

  string str() const

As you can see here, your str() is declared as returning a std::string, but the actual code does not return anything.

This is called "undefined behavior", and you cannot expect any meaningful results from this point on.

You will need to fix this str() method so they its either declared as returning a void, or actually returns a std::string, correctly.

All modern C++ compilers will issue a warning or a diagnostic message about this common bug. If your compiler produced a warning message when you compiled your code, this would be an example of not ignoring any kind of messages from your compiler. If you did not get any message from your compiler, check its settings and command-line options, and turn on all warning messages, or upgrade your compiler.

Upvotes: 4

Related Questions