Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ iterate one item - UB or defined behaviour?

I've been thinking about the rules for pointer arithmetic in c++ recently, having learned that pointer arithmetic is only defined for pointers that point at objects that exist in an array.

This led me to wonder whether the following code's behaviour is strictly undefined according to the standard.

Can anyone shed any light?

#include <iostream>
#include <algorithm>
#include <iterator>
#include <utility>
#include <string>
#include <vector>

struct Thing {
    std::string val;
};

int main() {

    Thing a_thing;

    std::vector<Thing> things;

    // take address
    auto first_thing = std::addressof(a_thing);  

    // take address of "one past the end" - UB?
    auto last_thing = std::next(first_thing);    

    // copying exactly one item, but is it UB?
    std::copy(first_thing, last_thing, std::back_inserter(things));  
}
like image 483
Richard Hodges Avatar asked Nov 25 '25 12:11

Richard Hodges


1 Answers

According to 5.7 [expr.add] paragraph 4 a pointer to an object behaves like a pointer the first object of a one element array:

For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

like image 134
Dietmar Kühl Avatar answered Nov 28 '25 03:11

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!