const string in the header file - solutions?

  • Thread starter C. Jayachandran
  • Start date
C

C. Jayachandran

I've inherited some code which has const std::string values defined in
a header file, like

const std::string str = "foo";

This causes a large amount of bloat, as all the compilation units
including this header file will have a copy of the string, as well as
code to construct and destruct the string, even if the string is not
used within the CPP file.

I cannot use the straight-forward solution of converting the 'const' to
'extern const' because this would involve adding a new library, which
is not possible at this point.

The only solution I can think of which will avoid most of the bloat is
to change the definition to:

inline const std::string &get_const_str() { static const std::string s
= "foo"; return s; }

But this would mean turning the const variable to a function. I would
really appreciate any suggestions on how to get a similar effect
without converting the constants to functions, any GCC specific trick
will do too...

Thanks,
JC.
 
A

Alf P. Steinbach

* C. Jayachandran:
I've inherited some code which has const std::string values defined in
a header file, like

const std::string str = "foo";

This causes a large amount of bloat, as all the compilation units
including this header file will have a copy of the string, as well as
code to construct and destruct the string, even if the string is not
used within the CPP file.

I cannot use the straight-forward solution of converting the 'const' to
'extern const' because this would involve adding a new library, which
is not possible at this point.

The only solution I can think of which will avoid most of the bloat is
to change the definition to:

inline const std::string &get_const_str() { static const std::string s
= "foo"; return s; }

But this would mean turning the const variable to a function. I would
really appreciate any suggestions on how to get a similar effect
without converting the constants to functions, any GCC specific trick
will do too...

The first you should do is _measure_ whether it actually makes a
difference.

If it really really matters, then you can use the template constant
trick (patent pending... ;-) ),

template< typename T >
struct Strings_{ static const std::string str; };

template< typename T >
std::string const Strings_<T>::str = "foo";

typedef Strings_<void> Strings;

int main()
{
std::cout << Strings::str << std::endl;
}

Hth.
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top