Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluation order initialization array in c++

I like c++11 variadic templates, so I often write some little codes with it.

See this example:

#include <cstdio>
#include <type_traits>
#include <vector>

template< typename ... T >
auto make_vector(T ... t ) -> std::vector< typename std::common_type<T...>::type >
{
    std::vector< typename  std::common_type<T...>::type > v;
    v.reserve( sizeof...(T) );

    using list = int[];
    (void)list{ 0, ( (void)v.push_back(std::move(t)) ,0)... };
    //                |/ / / /
    //                --------
    //                 \-- How are evaluated v.push_back()s, sequentially or arbitrary ?
    return v;
}

int main()
{
    auto v = make_vector(2, 3.0, 'a', 7UL );

    for(auto e : v )
      printf("%.2lf ", e);

    printf("\n");

}

Q: Is evaluation order of initialization of array sequentially or arbitrary (or implementation defined, undefined behavior) ?

If make_vector is wrong, how me fix its?

like image 616
Khurshid Avatar asked Nov 25 '13 06:11

Khurshid


People also ask

What is array initialization in C?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

Does C initialize arrays to 0?

Initialize Arrays in C/C++ c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

How can we declare and initialize array of strings in C?

A more convenient way to initialize a C string is to initialize it through character array: char char_array[] = "Look Here"; This is same as initializing it as follows: char char_array[] = { 'L', 'o', 'o', 'k', ' ', 'H', 'e', 'r', 'e', '\0' };


1 Answers

They are evaluated sequentially. C++11 § 8.5.4 [dcl.init.list] paragraph 4:

Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions (14.5.3), are evaluated in the order in which they appear.

Given that vector has an initializer_list constructor, you could simplify your function to:

template <typename ... T>
auto make_vector(T ... t) ->
  std::vector< typename std::common_type<T...>::type >
{
  return { static_cast<typename std::common_type<T...>::type>(t)... };
}

and not have to worry about arcane initialization semantics ;)

like image 60
Casey Avatar answered Sep 27 '22 21:09

Casey