C++ Default argument for vector&?

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);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)