4

If I have an aggregate struct, with default initializers for its members. If I value initialize the aggregate, are the members initialized with the initializers, or are they value initialized?

#include <unordered_map>
#include <array>
#include <iostream>
struct Foo{
    std::array<bool, 2> x = {true, true};
};

int main(){
    std::unordered_map<int, Foo> f;
    std::cout << f[0].x[1];
}

unordered_map::operator[] value initialize the value_type if the key does not exist. Does value initialization of Foo use my default initializer? Is the program guaranteed to output 1?

1 Answer 1

2

Yes.

The map's element initialisation will be via default constructor.

And, per my previous answer on the subject, this honours your default initializer.


[unord.map.elem]: mapped_type& operator[](const key_type& k);
1/ Effects: Equivalent to: return try_­emplace(k).first->second;

 

[unord.map]: template<class... Args> pair<iterator, bool> try_emplace(const key_type& k, Args&&... args);
6/ Effects: If the map already contains an element whose key is equivalent to k, there is no effect. Otherwise inserts an object of type value_­type constructed with piecewise_­construct, forward_­as_­tuple(k), forward_­as_­tuple(std::forward<Args>(args)...).

 

[pairs]: template<class... Args1, class... Args2> constexpr pair(piecewise_construct_t, tuple<Args1...> first_args, tuple<Args2...> second_args);
/15: Effects: Initializes first with arguments of types Args1... obtained by forwarding the elements of first_args and initializes second with arguments of types Args2... obtained by forwarding the elements of second_­args. (Here, forwarding an element x of type U within a tuple object means calling std::forward<U>(x).) This form of construction, whereby constructor arguments for first and second are each provided in a separate tuple object, is called piecewise construction.

(recall that Args2... is empty here, so no constructor arguments are provided to Foo, but the mechanism is still that as for constructor usage)

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

2 Comments

Thank you. If the Foo is defined as struct Foo{ std::array<bool, 2> x; }; Is the program guaranteed to output 0?
@Hui I don't believe so

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.