Creating const data

A

Andrew Chalk

I have a variable that is initialized with a value read from a configuration
file. Once initialized, it should not be changed anywhere in my program.
What is the best way to enforce this (it should be treated as const)?
Ideally, I would like a violation to generate a compile-time error.

Many thanks.
 
I

Ian Collins

Andrew said:
I have a variable that is initialized with a value read from a configuration
file. Once initialized, it should not be changed anywhere in my program.
What is the best way to enforce this (it should be treated as const)?
Ideally, I would like a violation to generate a compile-time error.
Use a const member of a class or struct:

struct X {
const int value;

X( int v ) : value(v) {}
};

X constants( whatEver );
 
A

Alf P. Steinbach

* Andrew Chalk:
I have a variable that is initialized with a value read from a configuration
file. Once initialized, it should not be changed anywhere in my program.
What is the best way to enforce this (it should be treated as const)?
Ideally, I would like a violation to generate a compile-time error.

In addition to Ian Collins' reply, you can do

Type const myVariable = valueFromConfigFile();

which for purposes of handling exceptions etc. you can put inside a
function, with lazy initialization (singleton pattern)

Type const& value()
{
static Type const theValue = valueFromConfigFile();
return theValue;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,220
Latest member
MathewSant

Latest Threads

Top