Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: "const int&"?

35 views
Skip to first unread message

Alf P. Steinbach

unread,
Jan 11, 2016, 12:33:52 AM1/11/16
to
On 1/11/2016 1:05 AM, Stefan Ram wrote:
> »Ignoring defaulted optional allocator parameters for
> simplicity, the two constructors are: vector( size_t n,
> const int& value ); // A: n copies of value«
>
> herbsutter.com/2013/05/09/gotw-1-solution/
>
> Why is there a reference in »const int& value« instead of
> just »const int value«?

Because `std::vector` is a class template, where this argument type is
specified in terms of a template parameter.

It's not practical to define a type-dependent choice of a formal
argument type in a template, because that would foil ordinary template
argument type deduction. So that's not done. So there's just a single
argument form for this argument, namely `T const&`, regardless of
whether that's maximally efficient or not for a given type `T`.

Cheers & hth.,

- Alf

SG

unread,
Jan 11, 2016, 9:39:50 AM1/11/16
to
On Monday, January 11, 2016 at 6:33:52 AM UTC+1, Alf P. Steinbach wrote:
> On 1/11/2016 1:05 AM, Stefan Ram wrote:
> > »Ignoring defaulted optional allocator parameters for
> > simplicity, the two constructors are: vector( size_t n,
> > const int& value ); // A: n copies of value«
> >
> > herbsutter.com/2013/05/09/gotw-1-solution/
> >
> > Why is there a reference in »const int& value« instead of
> > just »const int value«?
>
> Because `std::vector` is a class template, where this argument type is
> specified in terms of a template parameter.
>
> It's not practical to define a type-dependent choice of a formal
> argument type in a template, because that would foil ordinary template
> argument type deduction.

Well, it is possible to do something type-dependent and template
argument deduction is of no concern in this case. But I would claim
that something like this...

template<class T> // intentionally ignoring allocators
class vector {
...
vector(size_type n,
typename boost::call_traits<T>::param_type value = T());
...
};

...is not worth the effort at all. But this would pick pass-by-value
for small trivial types and pass-by-const-ref otherwise. So,
technically, it is possible.

Cheers!
SG

Alf P. Steinbach

unread,
Jan 11, 2016, 10:57:05 AM1/11/16
to
Hm. I was thinking about a dependent-on-actual-argument-type, and that
was wrong. Thanks.

The above is also a bit wrong, for C++11 and later, in that it limits
the item type T to types that can be default-initialized: in C++11 the
declaration of this constructor simply drops the default.

I think this means that the issue is not completely trivial. ;-)


Cheers,

- Alf

0 new messages