How do I write complex initialization?--Stack Overflow

Quick A: Initialize it using a lambda that’s invoked immediately.

Recently on SO:

Best practice for declaring variable without initialising it, so auto is unavailable

I want to declare two variables of the same type, and have the compiler figure out the types. However I don’t want to initialise one of the variables until later. I don’t think I can use auto here, so what’s the best option?

  1. std::vector<int> v;
  2.  
  3. // `start` and `end` should be the same type
  4. auto start = v.begin();
  5. ??? end;
  6.  
  7. // complicated code to assign a value to `end` (i.e. putting
  8. // the code in a function or using ?: is not practical here)
  9. if (...) {
  10. end = ...;
  11. } else {
  12. end = v.end();
  13. }

What’s the best way to tell the compiler that end should be the same type as start, but without having to initialise the variable?

  1. auto start = v.begin(), end; // Doesn't work, `end` has to be initialised
  2. decltype(start) end; // Does work, but not sure if it's best practice

Update

A couple of comments have suggested ways that would work in certain situations, so I am clarifying my situation here:

  1. std::vector<int> v;
  2. int amount = 123;
  3.  
  4. // `start` and `end` should be the same type
  5. auto start = v.begin();
  6. ??? end;
  7.  
  8. // code to assign a value to `end`
  9. if (amount) {
  10. end = start + amount;
  11. amount = 0;
  12. } else {
  13. end = v.end();
  14. }

I believe a lamda function would be trickier here, because amount is being reset to 0 after end is calculated, so in a lamda function that calculates a value for end, amount = 0 would have to come after the return statement. The only option would be to create more local variables, which would incur an (admittedly tiny) performance penalty.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.