The function accepts a reference parameter with a default value.

Based on http://www.cplusplus.com/reference/stl/vector/vector/

explicit vector ( const Allocator& = Allocator() );

This vector constructor accepts a reference parameter, which has a default value for Allocator (). What I learned from this function signature is that the function can accept a reference parameter with a default value.

This is the demo code that I am playing back with VS2010.

#include "stdafx.h"
#include <iostream>

using namespace std;

void funA(const int& iValue=5) // reference to a template const int 5 why?
{
    cout << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    funA();
    funA(10);
    return 0;
}

Are there any rules for using this syntax (i.e. a reference parameter with a default value)?

+3
source share
3 answers

References to Const can be tied to temporary objects, in which case the lifetime of the temporary object extends to the lifetime of the link.

+12

ยง 8.3.6 5 ++ 03:

( 4) . , , - (8.5).

, const Type& var = val , . ยง 8.5.3 5, . const Allocator& = Allocator() :

  •   
  • (.. cv1 const). [...]     
    •       
    • rvalue, T2 , " cv1 T1" " cv2 T2" ( ):

              
      •           
      • , rvalue (. 3.10) - .          
      • " cv2 T2" [sic], rvalue . - .        
              

      , , , . [...]

                  
    • , [...]

          
      

const int& iValue=5 :

  •   
  • (.. cv1 const). [...]     
    •       
    • rvalue [...]

            
    • " cv1 T1" , (8.5). . T1 T2, cv1 cv-, cv-, CV2; . [:

                const double& rcd2 = 2;         // rcd2  refers to temporary with value 2.0
                const volatile int cvi = 1;
                const int& r = cvi;             //  error: type qualifiers dropped
      
      --- ]           
      

, , , , . , . . orthogonal, , , (, , , , r, , rvalue).

+2

The only rules that I can think of are (a) that the link must be constant, because you cannot bind a non-constant link to a temporary one, and (b) that it is usually best not to use const references to skip built-in types. In other words:

(and)

void f(T& t = T(23)) {} // bad

void g(const T& t = T(23)) {} // fine

(b)

void f(const int& i = 23) {} // sort of ok

void g(int i = 23) {} // better
+2
source

Source: https://habr.com/ru/post/1773548/


All Articles