ऐसे मामले क्या हैं जहां reinterpret_cast
char*
(या char[N]
) अनिर्धारित व्यवहार है, और यह कब परिभाषित व्यवहार है? इस प्रश्न का उत्तर देने के लिए मुझे अंगूठे का नियम क्या उपयोग करना चाहिए?reinterpret_cast, char *, और अपरिभाषित व्यवहार
alignas(int) char data[sizeof(int)];
int *myInt = new (data) int; // OK
*myInt = 34; // OK
int i = *reinterpret_cast<int*>(data); // <== UB! have to use std::launder
लेकिन क्या बिंदु पर हम एक char
सरणी पर एक reinterpret_cast
कर सकते हैं और यह नहीं व्यवहार अपरिभाषित जा चुके हैं:
हम निम्नलिखित, this question से सीखा के रूप में अपरिभाषित व्यवहार है?
नहीं
new
, बसreinterpret_cast
:: यहाँ कुछ सरल उदाहरण हैंalignas(int) char data[sizeof(int)]; *reinterpret_cast<int*>(data) = 42; // is the first cast write UB? int i = *reinterpret_cast<int*>(data); // how about a read? *reinterpret_cast<int*>(data) = 4; // how about the second write? int j = *reinterpret_cast<int*>(data); // or the second read?
कब होता
int
शुरू करने के लिए जीवन भर? क्या यहdata
की घोषणा के साथ है? यदि हां, तोdata
का जीवनकाल कब समाप्त होता है?क्या होगा अगर
data
एक सूचक थे?char* data_ptr = new char[sizeof(int)]; *reinterpret_cast<int*>(data_ptr) = 4; // is this UB? int i = *reinterpret_cast<int*>(data_ptr); // how about the read?
क्या होगा यदि मैं बस तार पर structs प्राप्त कर रहा हूँ और सशर्त क्या पहले बाइट है के आधार पर उन्हें कास्ट करना चाहते हैं?
// bunch of handle functions that do stuff with the members of these types void handle(MsgType1 const&); void handle(MsgTypeF const&); char buffer[100]; ::recv(some_socket, buffer, 100) switch (buffer[0]) { case '1': handle(*reinterpret_cast<MsgType1*>(buffer)); // is this UB? break; case 'F': handle(*reinterpret_cast<MsgTypeF*>(buffer)); break; // ... }
इन मामलों यूबी के किसी भी कर रहे हैं? क्या वे सभी हैं? क्या इस प्रश्न का उत्तर सी ++ 11 से सी ++ 1z के बीच बदलता है?
** (1) ** मेरे लिए मान्य दिखता है। दोनों बयानों में, एक नई 'int' ऑब्जेक्ट को स्वीकार किया जाता है और एक मान असाइन किया जाता है। * पढ़ना * वह मान वह जगह है जहां चीजें बालों वाली हो रही हैं। ** (2) ** के साथ ही (मानते हुए 'आकार (int) == 4')। ** (3) ** मुझे यूबी की तरह दिखता है। –
@ इगोरटैंडनिक ने कुछ पढ़ने के साथ प्रश्नों को फिसल दिया, और 'आकार (int)' के बारे में धारणा से छुटकारा पा लिया, धन्यवाद। – Barry
अब ** (1) ** और ** (2) ** यूबी को लिंक किए गए प्रश्न के समान आधार पर प्रदर्शित करने लगते हैं। पहली कास्ट से पॉइंटर को सहेजकर और बाद के सभी लिखने और पढ़ने के लिए इसका उपयोग करके बचाया जाना आसान होगा। –