Should I pass a struct by the struct for string?

Jun 29, 2020 at 6:39pm
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");
}
Jun 29, 2020 at 6:47pm
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.
Jun 29, 2020 at 6:49pm
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?
Jun 29, 2020 at 7:01pm
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".
Jun 29, 2020 at 8:42pm
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 Jun 29, 2020 at 8:46pm
Jun 29, 2020 at 8:59pm
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.