Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify in C++ that a pointer points to data that is always valid?

Tags:

c++

constants

In a function parameter that is a pointer (foo(void *bar)), you can use const to specify that either the pointer (the parameter) itself is constant (foo(void * const bar)), and/or the data that the pointer points to is constant (foo(void const *bar)).

However in the foo(void const *bar) case, this is just a guarantee to the caller that foo will not attempt to modify the data pointed to by bar. It does not give bar any guarantee to foo that the memory location pointed to by bar will always be valid.

In cases where you are working with constant data within an executable image, if you could provide that guarantee to foo and if foo needed to keep a reference that data for longer than the duration of the function call, foo could simply keep a copy of the pointer rather than having to make a copy of the data.

Is there a way to encode this guarantee in the C++ type system?

Thanks.

like image 929
Matt Avatar asked Feb 20 '23 07:02

Matt


2 Answers

Q: Is there a way to specify in C++ that a pointer points to data that is always valid?

A: No. You are always empowered with the ability to shoot yourself in the foot :)

like image 197
paulsm4 Avatar answered Apr 06 '23 00:04

paulsm4


Not with a raw pointer but you could use a shared_ptr or a unique_ptr instead which would communicate that the function has ownership of the pointer.

like image 34
Dirk Holsopple Avatar answered Apr 05 '23 22:04

Dirk Holsopple