lundi 29 juin 2015

Why use std::next instead of adding an integer to the pointer?

I just have a quick question. I can't figure out the benefits of using std::next over just adding the desired number of advancements to the pointer. A simple example:

 int main()
 {
     int arr [] = {1, 2, 3, 4, 5};
     cout << *(arr + 2) << ", ";    //example 1
     cout << *std::next(arr, 2) << endl;    //example 2
     return 0;
 }

Output: 3, 3

Logically, example 1 should be quicker, since no function is called, etc. Also, in the instance in which I ran this code, if I added a number that would cause the pointer to be out of bounds (e.g. 7), the compiler would throw an error in example 1, but would happily go ahead and give me a memory address in example 2. This contradicted what I thought at first: that std::next would give some kind of warning or something if the pointer was out of bounds.

Any enlightenment would be appreciated.

Aucun commentaire:

Enregistrer un commentaire