By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,406 Members | 888 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,406 IT Pros & Developers. It's quick & easy.

Creating const data

P: n/a
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.
Feb 21 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Andrew Chalk wrote:
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 );
--
Ian Collins.
Feb 21 '07 #2

P: n/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.
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;
}

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 21 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.