Reputation: 16439
I want to define a function that, when given an integer, will return a string. Like this:
# Pseudocode
function get_string(i)
return my_string_array[i]
end
The strings will be hard coded into the application. The function prototype is declared in a header file:
// header.h
const std::string &get_string(const int i);
The way I see it, I have two options for declaring the hard-coded strings.
Option #1: Declare a static variable in get_string
// source.cpp
const std::string &get_string(const int i)
{
static const std::string values[] = {
std::string("foo"),
std::string("bar"),
std::string("baz"),
};
// Assume bounds checking is performed on i.
return values[i];
}
Option #2: Declare global constant in an anonymous namespace
// source.cpp
namespace
{
const std::string values[] = {
std::string("foo"),
std::string("bar"),
std::string("baz"),
};
}
const std::string &get_string(const int i)
{
// Assume bounds checking is performed on i.
return values[i];
}
For this limited use-case, are these declarations functionally equivalent? Does the program treat static constants in functions differently from globally declared constants or constants declared in anonymous namespaces?
I'm aware of the obvious accessibility differences (i.e. constant declared in local namespace is available globally to all functions defined in the same translation unit), but that can be chalked up as an advantage either way depending on the scenario, so for the purposes of this question this difference can be omitted.
Upvotes: 0
Views: 920
Reputation: 50036
Strings defined as static array inside your get_string function will be constructed on the first get_string
call, while strings in global namespace will be constructed on application start.
So the problems that might arrise are different for both aproaches. For example if you go with defining strings at global scope then you should not use it before your main
is executed, otherwise you never know if they got constructed. If you go with static construction inside get_string
you may encounter threading problems at least until c++11, after that magic statics should fix this for you.
Why dont you put them inside const char*
global array?
[edit]
Global array is not the right way to do it, as I suggested above. Another thing for you to consider is to go with option 1, but instead of array of strings create array of const char*
string literals. Array of std::string object's will duplicate your string literals. You would have to probably also return const char*
- so maybe thats not what you want.
Upvotes: 2