From what I understand, {} is a way to initialize variables with some "safety" advantages over other methods, such as forbidding narrowing:
int some_int_a = 1.2; // narrows
int some_int_b (1.2); // narrows
int some_int_c {1.2}; // does NOT compile, cannot narrow
So far so good. The thing I recently discovered, that I do not understood fully, is when does this sort of check happen? For example, in the following code:
#include <iostream>
class ExClass{
private:
const int i;
public:
ExClass(int i=0): i{i} {
// needed even if empty
}
void print(void){
std::cout << "const int i = " << i << std::endl;
}
};
int main(void)
{
ExClass ex_a (2.3); // narrows! this was surprising to me, I (probably naively)
// expected i{i} in the constructor to forbid this.
ex_a.print();
ExClass ex_b {2.3}; // does not compile
ex_b.print();
return 0;
}
I suppose this means that in the case of ex_a, first an intermediate int is created fully with a narrowing conversion, then this intermediate int is used to bracket-initialize i in the constructor. While in the second case, the intermediate int cannot be bracket-initialized with a conflicting input, is that right?
Is there a way to write things in such a way that there is no "intermediate" narrowing, so that the class bracket initialization detects the faulty input?