Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

stl::list initialization problem 1

Status
Not open for further replies.

mariacri11

Programmer
Apr 9, 2003
22
0
0
CY
Hi all,

I want to initialize a static stl::list of strings with some predifined string values(hardcoded).

I declared the list in my class like this:

static const list<string> my_list;

(I want to do something like static const list<string> my_list("VAL1","VAL2","VAL3","VAL4") but this is not working.)

Does someone know how to solve this problem?
Thank you very much!

Cristina

 
You can't populate a list with constants using its constructor. You would have to use:
[tt]
std::list<string> my_list;
my_list.push_back("VAL1");
my_list.push_back("VAL2");
...
[/tt]
However, if your list is going to be constant, it might be simpler to use an array of char* strings instead.
 
What I usually end up doing in that case:
Code:
// Initialize a array of strings
static const char *values[] = {
  "VAL1",
  "VAL2",
  "VAL3",
  "VAL4",
  "VAL5"
};

// Determine the number of strings in the array
enum { nvalues = sizeof (values) / sizeof (values[0]) };

// Initialize a list using using the begin and end range
list<string> my_list (values, values + nvalues);
 
Except you're not supposed to use [tt]static[/tt] for that purpose in C++, so I probably should have done it like this:
Code:
namespace
{
  const char *values[] = {
    ...
  };

  enum { nvalues = ... };

  list<string> my_list (values, values + nvalues);
}
 
Why aren't you supposed to use static like that? I do it all the time.
 
I'm not really sure what the rationale for the recommendation is, and I can't find anything authorative that seems to explain it. I'm not even really sure where I read about it in the first place.

At any rate, using [tt]static[/tt] does work, and I doubt anything bad comes from using it for that purpose. I certainly forget to use unnamed namespaces (as evidenced by my first code sample). When I learned C++, I didn't really understand the concept of static and external linkage. I learned what it meant when I learned C, so the [tt]static[/tt] method stuck with me.
 
The static keyword (in C style for items localized in a module) is deprecated by the modern C++ Standard. The Standard recommends anonimous namespace in that case...
 
Thanks. I'll start using anonimous namespaces. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top