Allocate vector size with list initialization (curly braces)











up vote
11
down vote

favorite












How can I do the equivelant of:



#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer(bufferSize, ' ');


With list (curly braced) initialization?



When I try to do the following:



#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer {bufferSize, ' '};


It wrongly interprets bufferSize as the value to be stored in the first index of the container (i.e. calls the wrong std::vector constructor), and fails to compile due to invalid narrowing conversion from unsigned int (size_t) to unsigned char.










share|improve this question


















  • 9




    Why do you insist on doing this with "curly brace initialization"?
    – Max Langhof
    Nov 29 at 15:08






  • 5




    @MaxLanghof Well, it is called uniform initialization. One could be lead to believe it should be the preferred way to initialize an object ;)
    – NathanOliver
    Nov 29 at 15:10






  • 3




    @NathanOliver Related xkcd.com/927
    – liliscent
    Nov 29 at 15:12






  • 2




    @OP Here is a very good talk on the nightmare of C++ initialization: youtube.com/watch?v=7DTlWPgX6zs
    – NathanOliver
    Nov 29 at 15:12






  • 1




    @MaxLanghof because some recommend to use it everywhere as it is "safer" (does not have most vexing parse issue). In reality it is more dangerous.
    – Slava
    Nov 29 at 15:13















up vote
11
down vote

favorite












How can I do the equivelant of:



#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer(bufferSize, ' ');


With list (curly braced) initialization?



When I try to do the following:



#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer {bufferSize, ' '};


It wrongly interprets bufferSize as the value to be stored in the first index of the container (i.e. calls the wrong std::vector constructor), and fails to compile due to invalid narrowing conversion from unsigned int (size_t) to unsigned char.










share|improve this question


















  • 9




    Why do you insist on doing this with "curly brace initialization"?
    – Max Langhof
    Nov 29 at 15:08






  • 5




    @MaxLanghof Well, it is called uniform initialization. One could be lead to believe it should be the preferred way to initialize an object ;)
    – NathanOliver
    Nov 29 at 15:10






  • 3




    @NathanOliver Related xkcd.com/927
    – liliscent
    Nov 29 at 15:12






  • 2




    @OP Here is a very good talk on the nightmare of C++ initialization: youtube.com/watch?v=7DTlWPgX6zs
    – NathanOliver
    Nov 29 at 15:12






  • 1




    @MaxLanghof because some recommend to use it everywhere as it is "safer" (does not have most vexing parse issue). In reality it is more dangerous.
    – Slava
    Nov 29 at 15:13













up vote
11
down vote

favorite









up vote
11
down vote

favorite











How can I do the equivelant of:



#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer(bufferSize, ' ');


With list (curly braced) initialization?



When I try to do the following:



#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer {bufferSize, ' '};


It wrongly interprets bufferSize as the value to be stored in the first index of the container (i.e. calls the wrong std::vector constructor), and fails to compile due to invalid narrowing conversion from unsigned int (size_t) to unsigned char.










share|improve this question













How can I do the equivelant of:



#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer(bufferSize, ' ');


With list (curly braced) initialization?



When I try to do the following:



#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer {bufferSize, ' '};


It wrongly interprets bufferSize as the value to be stored in the first index of the container (i.e. calls the wrong std::vector constructor), and fails to compile due to invalid narrowing conversion from unsigned int (size_t) to unsigned char.







c++ c++11 list-initialization






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 29 at 15:04









not an alien

1799




1799








  • 9




    Why do you insist on doing this with "curly brace initialization"?
    – Max Langhof
    Nov 29 at 15:08






  • 5




    @MaxLanghof Well, it is called uniform initialization. One could be lead to believe it should be the preferred way to initialize an object ;)
    – NathanOliver
    Nov 29 at 15:10






  • 3




    @NathanOliver Related xkcd.com/927
    – liliscent
    Nov 29 at 15:12






  • 2




    @OP Here is a very good talk on the nightmare of C++ initialization: youtube.com/watch?v=7DTlWPgX6zs
    – NathanOliver
    Nov 29 at 15:12






  • 1




    @MaxLanghof because some recommend to use it everywhere as it is "safer" (does not have most vexing parse issue). In reality it is more dangerous.
    – Slava
    Nov 29 at 15:13














  • 9




    Why do you insist on doing this with "curly brace initialization"?
    – Max Langhof
    Nov 29 at 15:08






  • 5




    @MaxLanghof Well, it is called uniform initialization. One could be lead to believe it should be the preferred way to initialize an object ;)
    – NathanOliver
    Nov 29 at 15:10






  • 3




    @NathanOliver Related xkcd.com/927
    – liliscent
    Nov 29 at 15:12






  • 2




    @OP Here is a very good talk on the nightmare of C++ initialization: youtube.com/watch?v=7DTlWPgX6zs
    – NathanOliver
    Nov 29 at 15:12






  • 1




    @MaxLanghof because some recommend to use it everywhere as it is "safer" (does not have most vexing parse issue). In reality it is more dangerous.
    – Slava
    Nov 29 at 15:13








9




9




Why do you insist on doing this with "curly brace initialization"?
– Max Langhof
Nov 29 at 15:08




Why do you insist on doing this with "curly brace initialization"?
– Max Langhof
Nov 29 at 15:08




5




5




@MaxLanghof Well, it is called uniform initialization. One could be lead to believe it should be the preferred way to initialize an object ;)
– NathanOliver
Nov 29 at 15:10




@MaxLanghof Well, it is called uniform initialization. One could be lead to believe it should be the preferred way to initialize an object ;)
– NathanOliver
Nov 29 at 15:10




3




3




@NathanOliver Related xkcd.com/927
– liliscent
Nov 29 at 15:12




@NathanOliver Related xkcd.com/927
– liliscent
Nov 29 at 15:12




2




2




@OP Here is a very good talk on the nightmare of C++ initialization: youtube.com/watch?v=7DTlWPgX6zs
– NathanOliver
Nov 29 at 15:12




@OP Here is a very good talk on the nightmare of C++ initialization: youtube.com/watch?v=7DTlWPgX6zs
– NathanOliver
Nov 29 at 15:12




1




1




@MaxLanghof because some recommend to use it everywhere as it is "safer" (does not have most vexing parse issue). In reality it is more dangerous.
– Slava
Nov 29 at 15:13




@MaxLanghof because some recommend to use it everywhere as it is "safer" (does not have most vexing parse issue). In reality it is more dangerous.
– Slava
Nov 29 at 15:13












2 Answers
2






active

oldest

votes

















up vote
12
down vote



accepted










Short answer: you don't.



This is not a problem with uniform initialization per se, but with std::initializer_list. There is a special rule in overload resolution that always gives priority to constructors taking std::initializer_list if list-initialization is used, regardless of the existence of other constructors which might require less implicit conversions.





I would suggest using



std::vector<unsigned char> buffer(bufferSize, ' ');


or, if you really want to use list-initialization, create your wrapper around std::vector that provides constructor overloads that do the right thing.






share|improve this answer




























    up vote
    5
    down vote













    The two relevant overload of std::vector are:



    explicit vector( size_type count, 
    const T& value = T(),
    const Allocator& alloc = Allocator()); //(1)
    vector( std::initializer_list<T> init,
    const Allocator& alloc = Allocator() ); // (2)


    These two overload has clear meaning, where the second is used to initialize the vector with the elements of the std::initializer_list.



    Overload resolution prefer initializer-list constructors when list-initialization is used.



    Narrowing conversions are not allowed with list-initialization, you're trying to create a std::vector with T=unsigned char but the deduced T for the std::initializer_list parameter is T= unsigned long which will involve a narrowing conversion (not allowed).






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53541937%2fallocate-vector-size-with-list-initialization-curly-braces%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      12
      down vote



      accepted










      Short answer: you don't.



      This is not a problem with uniform initialization per se, but with std::initializer_list. There is a special rule in overload resolution that always gives priority to constructors taking std::initializer_list if list-initialization is used, regardless of the existence of other constructors which might require less implicit conversions.





      I would suggest using



      std::vector<unsigned char> buffer(bufferSize, ' ');


      or, if you really want to use list-initialization, create your wrapper around std::vector that provides constructor overloads that do the right thing.






      share|improve this answer

























        up vote
        12
        down vote



        accepted










        Short answer: you don't.



        This is not a problem with uniform initialization per se, but with std::initializer_list. There is a special rule in overload resolution that always gives priority to constructors taking std::initializer_list if list-initialization is used, regardless of the existence of other constructors which might require less implicit conversions.





        I would suggest using



        std::vector<unsigned char> buffer(bufferSize, ' ');


        or, if you really want to use list-initialization, create your wrapper around std::vector that provides constructor overloads that do the right thing.






        share|improve this answer























          up vote
          12
          down vote



          accepted







          up vote
          12
          down vote



          accepted






          Short answer: you don't.



          This is not a problem with uniform initialization per se, but with std::initializer_list. There is a special rule in overload resolution that always gives priority to constructors taking std::initializer_list if list-initialization is used, regardless of the existence of other constructors which might require less implicit conversions.





          I would suggest using



          std::vector<unsigned char> buffer(bufferSize, ' ');


          or, if you really want to use list-initialization, create your wrapper around std::vector that provides constructor overloads that do the right thing.






          share|improve this answer












          Short answer: you don't.



          This is not a problem with uniform initialization per se, but with std::initializer_list. There is a special rule in overload resolution that always gives priority to constructors taking std::initializer_list if list-initialization is used, regardless of the existence of other constructors which might require less implicit conversions.





          I would suggest using



          std::vector<unsigned char> buffer(bufferSize, ' ');


          or, if you really want to use list-initialization, create your wrapper around std::vector that provides constructor overloads that do the right thing.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 29 at 15:19









          Vittorio Romeo

          55.9k17149289




          55.9k17149289
























              up vote
              5
              down vote













              The two relevant overload of std::vector are:



              explicit vector( size_type count, 
              const T& value = T(),
              const Allocator& alloc = Allocator()); //(1)
              vector( std::initializer_list<T> init,
              const Allocator& alloc = Allocator() ); // (2)


              These two overload has clear meaning, where the second is used to initialize the vector with the elements of the std::initializer_list.



              Overload resolution prefer initializer-list constructors when list-initialization is used.



              Narrowing conversions are not allowed with list-initialization, you're trying to create a std::vector with T=unsigned char but the deduced T for the std::initializer_list parameter is T= unsigned long which will involve a narrowing conversion (not allowed).






              share|improve this answer



























                up vote
                5
                down vote













                The two relevant overload of std::vector are:



                explicit vector( size_type count, 
                const T& value = T(),
                const Allocator& alloc = Allocator()); //(1)
                vector( std::initializer_list<T> init,
                const Allocator& alloc = Allocator() ); // (2)


                These two overload has clear meaning, where the second is used to initialize the vector with the elements of the std::initializer_list.



                Overload resolution prefer initializer-list constructors when list-initialization is used.



                Narrowing conversions are not allowed with list-initialization, you're trying to create a std::vector with T=unsigned char but the deduced T for the std::initializer_list parameter is T= unsigned long which will involve a narrowing conversion (not allowed).






                share|improve this answer

























                  up vote
                  5
                  down vote










                  up vote
                  5
                  down vote









                  The two relevant overload of std::vector are:



                  explicit vector( size_type count, 
                  const T& value = T(),
                  const Allocator& alloc = Allocator()); //(1)
                  vector( std::initializer_list<T> init,
                  const Allocator& alloc = Allocator() ); // (2)


                  These two overload has clear meaning, where the second is used to initialize the vector with the elements of the std::initializer_list.



                  Overload resolution prefer initializer-list constructors when list-initialization is used.



                  Narrowing conversions are not allowed with list-initialization, you're trying to create a std::vector with T=unsigned char but the deduced T for the std::initializer_list parameter is T= unsigned long which will involve a narrowing conversion (not allowed).






                  share|improve this answer














                  The two relevant overload of std::vector are:



                  explicit vector( size_type count, 
                  const T& value = T(),
                  const Allocator& alloc = Allocator()); //(1)
                  vector( std::initializer_list<T> init,
                  const Allocator& alloc = Allocator() ); // (2)


                  These two overload has clear meaning, where the second is used to initialize the vector with the elements of the std::initializer_list.



                  Overload resolution prefer initializer-list constructors when list-initialization is used.



                  Narrowing conversions are not allowed with list-initialization, you're trying to create a std::vector with T=unsigned char but the deduced T for the std::initializer_list parameter is T= unsigned long which will involve a narrowing conversion (not allowed).







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 29 at 15:27

























                  answered Nov 29 at 15:21









                  Jans

                  6,80422233




                  6,80422233






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53541937%2fallocate-vector-size-with-list-initialization-curly-braces%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Probability when a professor distributes a quiz and homework assignment to a class of n students.

                      Aardman Animations

                      Are they similar matrix