4

I have below a structure and need to initialize the object of it using std::fill.

typedef struct _test
{
    char name[32];
    char key[4];
    int count;

}test;

As of now, I am using memset. I need to change it to std::fill. I have tried below but std::fill throws compiler error for the structure object.

test t;
char a[5];
std::fill(a, a + 5, 0);
std::fill(t, sizeof(t), 0);

Note: I don't want to initialize using this way. char a[5] = {0};

JFMR
  • 23,265
  • 4
  • 52
  • 76
Arun
  • 2,247
  • 3
  • 28
  • 51

1 Answers1

9

You don't need std::fill (or std::memset, on which you should read more here). Just value initialize the structure:

test t{};

This will in turn zero initialize all the fields. Beyond that, std::fill accepts a range, and t, sizeof(t) is not a range.

And as a final note, typedef struct _test is a needless C-ism. The structure tag in C++ is also a new type name. So what this does is pollute the enclosing namespace with a _test identifier. If you need C compatibility on the off-chance, the way to go is this

typedef struct test
{
    char name[32];
    char key[4];
    int count;

} test;

This sort of typedef is explicitly valid in C++, despite both the struct declaration and the typedef declaring the same type name. It also allows both C and C++ code to refer to the type as either test or struct test.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • the structure was defined in one of the C library. My application is making using of that structure. I dont have control on the C library. I will be reusing the same object in different part of code and I need to reset the values to 0. In this case I have to use memset. So I asked this question to know, is there a way to replace memset with std::fill – Arun Jan 03 '19 at 11:02
  • @Arun - The fact you want to use memset or fill doesn't change the fact you don't need either for this in C++. You wanted zeros, I provided an answer the gives zeros with no effort. – StoryTeller - Unslander Monica Jan 03 '19 at 11:04
  • And if you want to reset than `t = test{};` will do it just fine. – StoryTeller - Unslander Monica Jan 03 '19 at 11:08
  • Thanks for the information. I tried value initialization for an array. It is working same way as a structure. Is there any similar way for resetting arrays or I should go with std::fill or memset? – Arun Jan 03 '19 at 12:10
  • @Arun - Arrays would still require `std::fill`. Though if you use `std::array` it will have full value semantics too. – StoryTeller - Unslander Monica Jan 03 '19 at 12:21