Should I pass a struct by the struct for string?

closed account (Ey80oG1T)
I have a struct like this:

1
2
3
4
5
struct Token
{
  std::string type;
  std::string token;
}


And I have a function that compares a struct to a value. But should I do this:

1
2
3
4
bool ComapreStruct(const Token& token)
{
  return (token.token == "hello");
}


or:

1
2
3
4
bool ComapreStruct(const std::string& token)
{
  return (token == "hello");
}
It depends on what you are doing. But if you always have a Token and you always want to compare its token member, I would go with the first.

BTW, Having an object named token of a type named Token that contains a data member named token may become confusing as your code gets more complex. You might want to consider renaming some of these things.
closed account (Ey80oG1T)
oh yeah, that was just for the example. also, is passing a struct worse than passing a string? or is it fine as long as there's a reference?
It's fine as long as you use a reference.

An old friend of mine used to say that a reference had "the efficiency of a pointer and the semantics of an object".
I don't think you've provided enough information to decide on whether passing a reference to a Token or a std::string is more appropriate.

Knowing what the token member contains, which I assume is something more meaningful than a string like "hello", would help.

And the name CompareStruct() is rather vague; a function's name should clearly state what it does.

Also, functions called -compare- usually compare two things, e.g. strcmp() and std::string::compare()

Andy


Last edited on
If two tokens have the same "token" but different types, are they the same? I doubt it. You probably need to compare both type and string.

Also, consider doing this in operator==() instead. That way you can write things like if (tok1 == tok2) doStuff();
Topic archived. No new replies allowed.