Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

C++ Default argument for vector<int>&?

I have a function,

void test( vector<int>& vec );

How can I set the default argument for vec ? I have tried

void test( vector<int>& vec = vector<int>() );

But there's a warning "nonstandard extension used : 'default argument' : conversion from 'std::vector<_Ty>' to 'std::vector<_Ty> &'"

Is there a better way to do this ? Instead of

void test() {
    vector<int> dummy;
    test( dummy );
}

Regards, Voteforpedro

question from:https://stackoverflow.com/questions/3147274/c-default-argument-for-vectorint

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you tried:

void test(const vector<int>& vec = vector<int>());

C++ does not allow temporaries to be bound to non-const references.

If you really to need to have a vector<int>& (not a const one), you can declare a static instance and use it as a default (thus non-temporary) value.

static vector<int> DEFAULT_VECTOR;

void test(vector<int>& vec = DEFAULT_VECTOR);

But beware, because DEFAULT_VECTOR will (can) be modified and won't reset on each call ! Not sure that this is what you really want.


Thanks to stinky472, here is a thread-safe alternative:

Instead of providing a default value, you might as well overload test() with a zero-parameter version which calls the other version:

void test()
{
  vector<int> vec;
  test(vec);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...