In C++ where it's available, it's good practice to use auto for many variables, in particular those whose type is known but annoying to type out:
weird_template_type<int,char>::subtype::recursive_subtype some_function() {
// ...
}
// ...
auto val = some_function();
It's also good to use micro-scopes for RAII objects when that makes sense, e.g. for locking:
some_setup_code();
int val;
{
lock_guard<mutex> lk(mut);
val = read_shared_memory();
}
do_something(val);
Is there a way to mix these two idioms, e.g. when your shared-memory-reading code returns a strange type?
The obvious version doesn't work:
auto val;
{
lock_guard<mutex> lk(mut);
val = read_shared_memory();
}
do_something(val);
This fails at compile time due to an auto variable without an initializer.
Similarly, you can't declare the variable inside the scoped block, or else it isn't available later.
The only immediate options I can see are 1. type out the variable declaration explicitly (bleah), or 2. use auto with some other expression you know to be of the same type (not an improvement). Is there some other way?
Aucun commentaire:
Enregistrer un commentaire