से मैं इस तरह एक सी संरचना है:सी - अनुकरण 'परिवर्तनशील' सी ++
struct my_struct {
int i;
double d;
struct expensive_type * t;
};
इस संरचना का एक उदाहरण बनाया है और के रूप में आरंभ नहीं हो जाता:
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;
}
struct expensive_type * t
सदस्य गिना जा रहा है काफी है महंगा, और इसकी आवश्यकता नहीं हो सकती है - यह केवल NULL
के लिए शुरू किया गया है - और बाद में मांग पर गणना की गई:
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;
}
C++ में मैं struct expensive_type *
सदस्य पर mutable
इस्तेमाल किया गया होगा, यह संभव स्थानीय स्तर पर स्थिरांक दूर कास्टिंग सी में कुछ इसी तरह, यानी प्राप्त करने के लिए है:
{
struct my_struct * mutable_s = (struct my_struct*) s;
mutable_s->t = ...;
}
या हस्ताक्षर में const
को हटा रहा है मेरा एकमात्र मानक-अनुरूप विकल्प?
struct expensive; // Forward declaration, ignore
// One could also use a struct expensive * (a pointer) instead
// of this structure. IMO giving it a name is the better option.
struct expensive_handle {
struct expensive * target;
};
// Store the simple data members as usual, store a pointer to a
// handle (pointer) to the expensive ones
struct my_struct {
int simple;
struct expensive_handle * handle;
};
struct expensive {
int content; // whatever
};
बनाना एक my_struct
अतिरिक्त सूचक बनाने चाहिए/अविवेक के लिए इस्तेमाल किया संभाल:
struct my_struct * new() {
struct my_struct * data = malloc(sizeof(*data));
// Error handling please
// Set simple data members
data->handle = malloc(sizeof(*(data->handle)));
// Error handling please
data->handle->target = NULL;
return data;
}
सी – DyZ
में कोई 'म्यूटेबल' या उसके करीब कुछ भी नहीं है हां, 'const' को हटाने या यूबी पीड़ित करने की आवश्यकता है। हालांकि अच्छा पोस्ट। एक अच्छा जवाब सी spec उद्धृत करेगा। – chux
कोड को 'my_get_expensive (const struct my_struct * s) में' const' की आवश्यकता क्यों है? शायद वह लक्ष्य किसी अन्य तरीके से संतुष्ट हो सकता है? – chux