I have a C structure like this:
struct my_struct {
int i;
double d;
struct expensive_type * t;
};
An instance of this structure is created and initialized as:
struct my_struct * my_new( int i , double d)
{
struct my_struct * s = malloc( sizeof * s);
s->i = i;
s->d = d;
s->t = NULL;
return s;
}
Computing a member is struct expensive_type * t
quite expensive and may not be needed - for this, it is simply initialized to NULL
- and later calculated by request:
const struct expensive_type * my_get_expensive( const struct my_struct * s)
{
if (!s->t)
s->t = my_expensive_alloc( s->i , s->d );
return s->t;
}
In C ++, I would use mutable
in an element struct expensive_type *
whether it is possible to achieve something similar in C, that is, drop the constant locally:
{
struct my_struct * mutable_s = (struct my_struct*) s;
mutable_s->t = ...;
}
Or removes const
my only standard alternative in the signature?
source
share