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));
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With