(As discussed during lunch...)  Why not just do this in this case and remove
EmptyString() altogether?

const std::string& MyClass::foo() const {
  static std::string empty = EmptyString();
  return (everything == OK) ? member_string : empty;
}

I forget if this runs the constructor on first use or when the app starts
up.  If it's the latter and you care, you can even just make it a null
pointer and allocate it on first use.

No matter what PSA or comments you write, someone will use it again if it's
there.

J

On Thu, Jan 7, 2010 at 1:28 PM, Peter Kasting <[email protected]> wrote:

> If you have ever used any of the EmptyXXX() functions, or ever will, please
> read on.
>
> These functions (in string_util.h and gurl.h) are meant for a single,
> specific use case:
>
> const std::string& MyClass::foo() const {
>   return (everything == OK) ? member_string : EmptyString();
> }
>
> Here you cannot return "string()", because it's destroyed before the
> function returns, and the caller receives garbage; and you don't want to
> have the function return by value, because you can access the member
> variable directly and save a copy.  The utility functions give you a global
> empty string that you can safely return a const reference to.
>
> DON'T USE THESE OUTSIDE THIS CASE.  You should never use these as
> initializers, arguments to functions, or return values in functions that
> return by value.  Just use the default constructor; that's what it's there
> for.
>
> I have a change out for review that removes the erroneous uses of these
> from our codebase and clarifies the comment on their declaration, but it's
> worth calling this out directly so they don't creep back in.
>
> PK
>
> --
> Chromium Developers mailing list: [email protected]
> View archives, change email options, or unsubscribe:
>    http://groups.google.com/group/chromium-dev
>
-- 
Chromium Developers mailing list: [email protected] 
View archives, change email options, or unsubscribe: 
    http://groups.google.com/group/chromium-dev

Reply via email to