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?

std::vector<int> v;

// `start` and `end` should be the same type
auto start = v.begin();
??? end;

// complicated code to assign a value to `end` (i.e. putting
// the code in a function or using ?: is not practical here) 
if (...) {
    end = ...;
} else {
    end = v.end();
}

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?

auto start = v.begin(), end;  // Doesn't work, `end` has to be initialised
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:

std::vector<int> v;
int amount = 123;

// `start` and `end` should be the same type
auto start = v.begin();
??? end;

// code to assign a value to `end`
if (amount) {
    end = start + amount;
    amount = 0;
} else {
    end = v.end();
}

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.