Andreas
Andreas

Reputation: 7550

Can I avoid type redundancy in declaration-definitions?

Is there a way to avoid writing std::vector<int> twice on lines such as these?

std::vector<int>* numbers = new std::vector<int>(7);

(Typedefs don't count.)

Upvotes: 1

Views: 112

Answers (2)

John Dibling
John Dibling

Reputation: 101456

0) don't use new in the first place:

std::vector<int> numbers(7);

1) Use a typedef:

typedef std::vector<int> ints;
ints* numbers = new ints(7);

2) Use auto in C++11:

auto numbers = new std::vector<int>(7);

3) If you insist on using pointers, use a smart pointer:

std::unique_ptr<std::vector<int>> numbers(new std::vector<int>(7));

4) Use a maker function:

typedef std::vector<int> ints;
std::unique_ptr<ints>&& make_ints()
{
    return std::unique_ptr<ints>(new ints(7));
}

int main()
{
    std::unique_ptr<ints> numbers = make_ints();
}

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

Yes. In C++11 only:

auto numbers = new std::vector<int>(7); //C++11 only

Here the type of numbers is inferred by the compiler, and it turns out to be std::vector<int>* which is what you've written in your code.

But wait. Why would use new in the first place?

Do you have any strong reason for that? Most likely not. Use automatic object instead:

std::vector<int> numbers; //no new

Upvotes: 5

Related Questions