I found cases when a {}
-list is interpreted in different ways that can lead to subtle bugs. For example in this program (g++ 10.2.1):
#include <vector>
#include <iostream>
struct A {
int n1;
int n2;
//A(int _n1 = 0, int _n2 = 0): n1(_n1), n2(_n2) {}
};
int main() {
std::vector<A> v;
v.push_back({1,2});
std::cout << v.size() << std::endl;
v.insert(v.end(), {3,4});
std::cout << v.size() << std::endl;
}
Without a constructor in A
, insert
adds one element. Defining the constructor, insert
adds two elements, building an A
object for every number. This is because insert
(unlike push_back
) has different overloads for a single object or an initializer list. Of course this is not the case if you explicitly write A{3,4}
.
My questions:
- Is there a coherent line of reasoning to be aware of such cases?
- Are there other similar cases you know?
Aucun commentaire:
Enregistrer un commentaire