Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we can use the declared variable in its constructor in C++

I recently ran into some weird bugs due to this kind of code.

vector<int> a(a);

Why the code above is accepted? When is this necessary? And how to ask the compiler to forbid this kind of usage? Thank you.

like image 500
mr.pppoe Avatar asked Feb 25 '14 03:02

mr.pppoe


1 Answers

The most common use case for that is actually in C, not C++ (you should not use malloc in C++, although you can), but in this case C++ is backwards compatible:

mytype *p = malloc(sizeof *p);

By allowing the use of p in the initializer expression, you can pass sizeof *p to malloc ensuring that whatever the size of mytype is, the right size will be allocated. If you were not allowed to do *p, then the expression above would have to have the type mytype twice, and later maintenance in the code might update one of the types and fail to update the other.

like image 86
David Rodríguez - dribeas Avatar answered Nov 15 '22 16:11

David Rodríguez - dribeas