Effective walkthrough std :: vector

When a C ++ function takes an argument std::vector, a regular template should pass it by reference const, for example:

int sum2(const std::vector<int> &v)
{
   int s = 0;
   for(size_t i = 0; i < v.size(); i++) s += fn(v[i]);
   return s;
}

I believe this code leads to double dereferencing when accessing the elements of the vector, since the CPU must first dereference vto read the pointer to the first element that needs to be dereferenced to read the first element. I would expect it to be more efficient to pass a shallow copy of a vector object on the stack. Such a shallow copy encapsulates a pointer to the first element, and the size encapsulates a pointer to the same memory area as the original vector.

int sum2(vector_ref<int> v)
{
   int s = 0;
   for(size_t i = 0; i < v.size(); i++) s += fn(v[i]);
   return s;
}

, . : ? , - , .

: , , vector_ref . , .

+5
6

,

. . , [] ", .

+10

, :

  • , ( ), (const), ,
  • .

, , " ", . , STL. , , std- .

- ++, ++, , , .

, . , .

+9

?

: . : vector<int> const& .

+4

, . ( ), ( link-time) .

, , , . , , , . , ( ).

, , ( begin() end()) n ( ).

int sum(const vector<int> &v)
{
   int s = 0;
   for (auto it = v.begin(); it != v.end(); ++it) {
       s += fn(*it);
   }
   return s;
}

( , end() . , .)

STL. , , .

+2

, , , , . IDE , :

void Method(std::vector<int> const& vec) {
 int i = vec.back();
}


void SomeOtherMethod() {
  std::vector<int> vec;
  vec.push_back(1);
  Method(vec);
}

? . :

push        eax  // this is the constant one that has been stored in eax
lea         ecx,[ebp-24h] // ecx is the pointer to vec on the stack
call        std::vector<int,std::allocator<int> >::push_back

(), const &:

lea         ecx,[ebp-24h] 
push        ecx  
call        Method (8274DC0h) 

, , - , . () :

mov         ecx,dword ptr [ebp+8] 
call        std::vector<int,std::allocator<int> >::back (8276100h)

ecx.

+1