Question Details

No question body available.

Tags

c++ stdvector initializer-list

Answers (2)

Accepted Answer Available
Accepted Answer
October 5, 2025 Score: 3 Rep: 36,951 Quality: Expert Completeness: 80%

In order to work, this line:

foo.pushback( { 1 , fooString } );

has to copy fooString into the barChar member of the new bar element.

But C strings which are actually [zero terminated] char arrays are non-copyable (see e.g. here), hence the error.

The other case (foo.pushback( { 1 , "Hello" } );) is OK because you can initialize a C string with a string literal.

One solution is to create a temporary bar object to pushback into the std::vector.
Alternatively as @user7860670 commented, you can avoid the temporary by pushing a zero initialized bar and setting the fields afterwards in the element inside the vector.

Note:
Unlike C arrays, std::array is copyable.
If you can use it instead of the C array it might be the simplest solution.
However - in order to initialize an std::array with a string you need to use uniform initialization syntax: std::array fooString{"Hello"};.

A side note:
Instead of using a #define for your constant (MAX_LENGTH) you can consider to use a compile time constant (constexpr) which is considered more idiomatic.
See: Defining global constant in C++.

October 5, 2025 Score: 0 Rep: 5,351 Quality: Low Completeness: 40%

As @wohlstad pointed out, C arrays are non-copyable. I have to use the way of using a temporary bar variable, set the members and provide this to pushback()

    bar tempBar;

tempBar.barInt = 1; strcpy( tempBar.barChar, fooString ); foo.push
back( tempBar );