A function that always returns the same vector
I am trying to write a utility function that will return a vector. The returned vector will always have the same entries. I use it to filter the enum ( Directions
) so that clients can get the subset they want.
Here's an example of how I hope to approach the problem:
std::vector<Directions> horizontalDirections()
{
static std::vector<Directions> toReturn;
if (toReturn.size() == 0)
{
toReturn.push_back(Left);
toReturn.push_back(Right);
}
return toReturn;
}
Can this be done correctly?
source to share
How do you do it. But I would return the link const
so that it doesn't escape the copy if needed:
const std::vector<Directions>& horizontalDirections();
Also, if you are using C ++ 11, your implementation can be shortened as:
const std::vector<Directions>& horizontalDirections()
{
static std::vector<Directions> toReturn({Left, Right});
return toReturn;
}
If you're using C ++ 11, you can go even further and declare as horizontalDirections
global const vector
instead of a function:
const std::vector<Directions> horizontalDirections({Left, Right});
source to share
This is basically the correct idea. I would return with a link to avoid copying the vector. And you can make the body more readable with the C ++ 11 initializer style:
const std::vector<Directions>& horizontalDirections() {
static const std::vector<Directions> toReturn = {
Left,
Right
};
return toReturn;
}
source to share