-2

I have the following code:

typedef struct
{
    string name;
    int length;
}myStruct;

static myStruct getname()
{
    static myStruct name;

    if (name.length == 0)
    {
        name.value = "BLABLA";
            name.length = name.value.size();
    }

    return &name;
}

Is this code safe?? i.e can I guarantee that after constructing myStruct name, name.length will be equal to 0

simonc
  • 41,632
  • 12
  • 85
  • 103
Kam
  • 5,878
  • 10
  • 53
  • 97

4 Answers4

0

Yes, sort of, since static variables are zero-initialized. However, your code is not thread-safe. It would be better to say static myStruct name = initName();, which would be guaranteed to be executed only once.

Since there's also no point in storing the string length twice, your entire code could be simplified to this:

static std::string const & getName()
{
    static std::string impl("BLABLA");
    return impl;
}

Or even:

static const char * const name = "BLABLA";
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

Yes, name.length will be 0.

NOTE: You're returning &name which is a pointer to a myStruct whilst your code is declared to just return a myStruct

Sean
  • 60,939
  • 11
  • 97
  • 136
0
struct myStruct {
    string name;
    int length;
    myStruct(string name = "") : name(name), length(name.size()) {} 
};

static myStruct getname() {
    static myStruct name("BLABLA");
    return name;
}

Use the constructor initialization list, this is way safer. Here the length is initialized to the size of the name and it defaults to an empty string which has size == 0.

andre
  • 7,018
  • 4
  • 43
  • 75
0

There are different concepts of "safe" at play here.

The code as it stands is safe, because static variables are initialized to zero. (for more information)

However, I do not consider it "safe" because the initialization is non-obvious.
If another programmer tried to modify this code, they may not realize the importance of having name.length initialized to zero, and the fact that initialization is guaranteed by the static keyword.

The code as written makes it look like initialization is not in play, when in fact it is. I think at the very least you need to add a comment:

/* structure is initialized to all-zeros because it is static */
static myStruct name;
Community
  • 1
  • 1
abelenky
  • 63,815
  • 23
  • 109
  • 159