मेरे छोटे परीक्षणों के मुताबिक यह कोड काम करता है। लेकिन, क्या यह अपरिभाषित व्यवहार है? Const_cast के उपयोग के माध्यम से कॉन्स्ट ऑब्जेक्ट को संशोधित करने के परिणामस्वरूप मेरे पिछले परीक्षणों में रन-टाइम एक्सेस उल्लंघनों का परिणाम हुआ, लेकिन मुझे याद नहीं है कि वे अलग कैसे थे। तो, क्या मूल रूप से कुछ गलत है या नहीं?क्या const constcast के माध्यम से इस कॉन्स्ट प्रारंभिकता में अपरिभाषित व्यवहार है?
// test.h
#pragma once
#include <boost/array.hpp>
typedef boost::array<int,100000> bigLut_t;
extern const bigLut_t constBigLut;
// test.cpp
#include "test.h"
bigLut_t& initializeConstBigLut()
{
bigLut_t* pBigLut = const_cast<bigLut_t*>(&constBigLut);
for(int i = 0; i < 100000; ++i) {
pBigLut->at(i) = i;
}
return const_cast<bigLut_t&>(constBigLut);
}
const bigLut_t constBigLut = initializeConstBigLut();
// const_test.cpp
#include <iostream>
#include "test.h"
void main()
{
for(int i = 0; i < 100; ++i) {
std::cout << constBigLut[i] << std::endl;
}
system("pause");
}
(ध्यान दें कि sizeof (bigLut_t) ढेर में फिट बहुत ज्यादा है।)
संपादित करें: मैं वास्तव में ybungalobill के दशक में विचार की तरह इन बड़ी वस्तुओं को शुरू करने की विधि के लिए सबसे छोटी टिप्पणी:
// test.h
#pragma once
#include <boost/array.hpp>
extern const struct BigLut : public boost::array<int,100000> {
BigLut();
} constBigLut;
// test.cpp
#include "test.h"
const BigLut constBigLut;
BigLut::BigLut()
{
for(int i = 0; i < 100000; ++i) {
this->at(i) = i;
}
}
:
आप ऐसा कर सकता है। 'मुख्य' ** हमेशा ** वापसी प्रकार 'int' होना चाहिए। हालांकि, आप 'वापसी' कथन को सुरक्षित रूप से छोड़ सकते हैं। –