const vs. lazy initialization

I like lazy initialization like this:

const char *get_name(void) {
  if (NULL == name_) {
    name_ = generate_name();
  }
  return name_;
}

Lately I've also started liking const as a method modifier. This doesn't play nicely with lazy initialization:

char *get_name(void) const {
  if (NULL == name_) {
    name_ = generate_name(); <--- ERROR!
  }
  return name_;
}

I'm not sure how to elegantly combine the two.

Categories

2 Comments

dj said:

Brilliant!

The "mutable" keyword is what you want here. It lets you write methods like get_name() which are "conceptually const" but which internally update some cached state.

Eg. mutable const char * name_;

Leave a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About this Entry

This page contains a single entry by Mike Tsao published on April 26, 2004 1:19 PM.

More Eichler stuff was the previous entry in this blog.

Day 2 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.2-en