Mailinglist Archive: opensuse-programming (62 mails)

< Previous Next >
Re: [suse-programming-e] STL vector as a function parameter with default value (heres another one for you Jerry...)
  • From: Michael Stevens <mail@xxxxxxxxxxxxxxxxxx>
  • Date: Sat, 12 Feb 2005 11:52:53 +0100
  • Message-id: <200502121152.53200.mail@xxxxxxxxxxxxxxxxxx>
Brad,

On Friday 11 February 2005 21:03, Brad Bourn wrote:
> I have a fuction that takes a vector as a parameter.
>
> I want to be able to have a default value so I'm not required to pass
> anything if I don't need to.
>
> I pass vectors by reference because of some things I need to do with it
> that pointers don't do.
>
> anyway
>
>
> I can define my function like this
>
> func(vector<unsigned int> foo = vector<unsigned int>());
>
> and everthing is fine, however
> if I define like this,
>
> func(vector<unsigned int>& foo = vector<unsigned int>());

This is the same problem as you would get if you declared the function
func(vector<unsigned int>& foo);
and then called it with
func(vector<unsigned int>())

This is an error because 'vector<unsigned int>()' is a temporary and you can
only pass temporaries to 'const' reference parameters. Your function must be
declared
func(const vector<unsigned int>& foo);
OR
func(vector<unsigned int> foo);
to work with temporaries.

> I get
>
> error: invalid type `std::vector<unsigned int,
> std::allocator<unsigned int> >' for default argument to `
> std::vector<unsigned int, std::allocator<unsigned int> >&'
>
> I am running SuSE 9.1 2.6.5-7.145-default
>
> This syntax works with Borland 6 windoze (disclaimer: no, not mine,
> co-worker's)
Easy to explain. The ability to pass temporaries to non-const reference
parameters has been disallowed for years in standard C++. It is incredibly
dangerours. Some compilers support it despite this!

Michael

--
___________________________________
Michael Stevens Systems Engineering

Navigation Systems, Estimation and
Bayesian Filtering
http://bayesclasses.sf.net
___________________________________

< Previous Next >
Follow Ups
References