1

I have Const variable :

#define     ERROR_ME        std::string("Error Message")

in the function, I want return std::vector so, I write this:

return std::vector<byte>(ERROR_ME.begin(), ERROR_ME.end()); // this have error

can you help me?

1
  • 2
    Please don't use #define to declare constants. If you want a constant use const datatype = something;. Commented Aug 31, 2017 at 11:38

1 Answer 1

6

No you don't have a "Const [sic] variable", you have a symbolic constant that is replaced in the source before the compiler proper gets a chance to read it.

The code the compiler will see is not

return std::vector<byte>(ERROR_ME.begin(), ERROR_ME.end());

but instead

return std::vector<byte>(std::string("Error Message").begin(), std::string("Error Message").end());

That is, you get the begin and end iterators from two different and unrelated objects. Comparing or other interacting of unrelated iterators leads to undefined behavior.

If you want a true constant then use e.g.

std::string const ERROR_ME = "Error Message";
Sign up to request clarification or add additional context in comments.

1 Comment

this return std::vector<byte>(std::string("Error Message").begin(), std::string("Error Message").end()); not work, but when i use const variable it's ok(std::string const ERROR_ME = "Error Message";), tanx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.