Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value returned from a function with a const range as arguments

Tags:

c++

lets say I have a function

auto found = find(first, last, condition);

This find should be able to promise not to modify first to last.

So something like

auto find(const T* first, const T* last, Comp c = less<>);

results in a const T or const T* being returned.

so

int arr[] = {3, 4};
std::vector v(arr, arr +2);
int* found = find(v.begin(), v.end());
** error found is non-const.

I want to modify *found! What are my options? overloads?

like image 628
Captain Giraffe Avatar asked Feb 01 '26 20:02

Captain Giraffe


1 Answers

You cannot have that signature

int* my_find(const int* begin, const int* end);

(to signaling that your method doesn't modify the range) without (dangerous) /*const_*/cast.

That signature would allow

const int arr[] = {0, 1, 2, 3};

*my_find(std::cbegin(arr), std::cend(arr)) = 42; // Modifying const object. -> UB

Possibility would be, at the call site, to do all the casting:

// const int* my_find(const int*, const int*);
int arr[] = {0, 1, 2, 3};

auto it = const_cast<int*>(my_find(std::cbegin(arr), std::cend(arr)));

That assumes though that returned pointer is in range, and not pointer on external const object (signatures can't ensure that (Rust has additionally lifetime in type which enforces a little more that assumption :) )).

like image 61
Jarod42 Avatar answered Feb 03 '26 08:02

Jarod42



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!