C++/C++11 Efficient way to have static array/vector of objects initialized with initializer list, and supporting range-based for

后端 未结 3 438
北恋
北恋 2020-12-15 07:29

Suppose you want to have a static array of pre-defined values/objects (const or non-const) associated with a class. Possible options are to use std:vector,

3条回答
  •  Happy的楠姐
    2020-12-15 08:04

    Here is a way to set up the vector without copies or moves.

    It doesn't use a braced initializer but your opening paragraph suggests that your main concern is avoiding copies and moves; rather than an absolute requirement to use a braced initializer.

     // header
    const std::vector &get_vec();
    
    // cpp file
    const std::vector &get_vec()
    {
        static std::vector x;
    
        if ( x.empty() )
        {
            x.emplace_back(1,2,3);
            x.emplace_back(4,5,6);
            // etc.
        }
    
        return x;    
    }
    

提交回复
热议问题