1

I have a class respectively a struct with a member variable of type std::array<char, 100> called charArray. I want to initialize this array sensibly. Which values are sensible to init the array with and what is the best way to do this?

I think I could use std::fill() in constructor but is this the way I should really do it? I mean because of initialization vs. assignment?

Thanks.

1 Answer 1

1

A simple solution would be to value initialize the array to the type's default value. Take for example

struct Foo
{
    std::array<int, 10> bar;
    Foo() : bar({}) {}
};

Here bar is would be initialized to all 0's. You can compare that with

struct Bar
{
    std::array<int, 10> baz;
};

Which would default initialize baz and its elements would have an indeterminate value. You can see all of this working with

struct Foo
{
    std::array<int, 10> bar;
    Foo() : bar({}) {}
};

struct Bar
{
    std::array<int, 10> baz;
};


int main(){
    Foo foo;
    for (auto e : foo.bar)
        std::cout << e << " ";
    std::cout << std::endl;
    Bar bar;
    for (auto e : bar.baz)
        std::cout << e << " ";
}

Possible output:

0 0 0 0 0 0 0 0 0 0 
-917263728 4197632 4197632 4197632 4197632 4197632 6295552 0 4197581 0 

Live Example

Sign up to request clarification or add additional context in comments.

6 Comments

Did you mean "baz' elements would have an indeterminant value"?
@PeterA.Schneider Typo Fixed. Thanks for spotting it.
@PeterA.Schneider I am not sure if reading them is UB or not.
It's a bit hidden, but 4.1 in the 2011 standard makes any "lvalue-to-rvalue" conversion (which must happen somewhere to the elements of bar.baz behind the screen of iterators and operator calls) undefined behavior "if the object is uninitialized". DR 616 will not change that for automatic variables. The reason must be architectures with "uninitialized" flags or outright trap representations in registers.
@PeterA.Schneider But since the array values get default initialized does that still count?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.