I've noticed that, in addition to initialization, I'm able to assign initializer lists to STL containers such as std::array and std::vector. For example:
#include <iostream>
#include <array>
#include <vector>
using namespace std;
int main()
{
array<int, 4> arr;
vector<int> vec(4);
arr = 1;
vec = {4, 3, 2, 1};
cout << "arr: ";
for (auto elem : arr)
cout << elem << " ";
cout << "\nvec: ";
for (auto elem : vec)
cout << elem << " ";
cout << endl;
}
I'm compiling this code on Clang 3.8.0 with just the -std=C++11 flag. I'm trying to discern whether this behavior is defined by the C++11 standard, or just the compiler. I've been trying to make my way through the relevant parts of the standard (and cppreference.com when the language in the standard gets too complex) and so far have come up with this:
Initializer Lists
5.17.9 - a brace-init-list may appear on the right hand side of an assignment defined by a user-defined assignment operator
std::array
23.3.2.2: class array relies on implicitly-declared special member functions ... to conform to container requirements
std::vector
vector& operator=( std::initializer_list ilist );
- Replaces the contents with those identified by initializer list ilist. (Since C++11)
From the syntax of the overloaded assignment operator for std::vector it seems clear that assignment by an initializer list is supported. So I'm wondering if passing an initializer list to the overloaded assignment operator implicitly defined for STL containers (std::array in my example) is defined behavior? As a bonus, is std::array the only STL container with an implicitly defined overloaded assignment operator?
I've looked at a answers to related questions on SO such as:
how to assign an array from an initializer list
Error: Assigning to an array from an initializer list
However the answers given do not coincide with behavior I'm getting from my compiler, or what I'm interpreting from the standard. Also, I'm looking for an answer to a more general question than just assigning list initializers to std::array.
Aucun commentaire:
Enregistrer un commentaire