views:

88

answers:

2

Hello everyone.

Rather simple question. Where should I store error,exception, user messages? By far, I always declared local strings inside the function where it is going to be invoked and did not bother. e.g.

SomeClass::function1(...)
{
std::string str1("message1");
std::string str2("message2");
std::string str3("message3");
...
// some code
...
}

Suddenly I realized that since construction & initialization are called each time and it might be quite expensive. Would it be better to store them as static strings in class or even in a separate module? Localization is not the case here.

Thanks in advance.

+5  A: 

Why not just use a string constant when you need it?

SomeClass::function1(...)
{
/* ... */
    throw std::runtime_error("The foo blortched the baz!");
/* ... */
}

Alternately, you can use static const std::strings. This is appropriate if you expect to copy them to a lot of other std::strings, and your C++ implementation does copy-on-write:

SomeClass::function1(...)
{
    static const std::string str_quux("quux"); // initialized once, at program start
    xyz.someMember = str_quux; // might not require an allocation+copy
}

If you expect to make lots of copies of these strings, and you don't have copy-on-write (or can't rely on it being present), you might want to look into using boost::flyweight.

bdonlan
Most current implementations do not perform copy-on-write. The advantage they provide (performance-wise) is outperformed by the amount of trouble to get it to be thread safe. To deal with multithreaded environments you would have to add locks to protect all operations (both read and write) which ends up in quite a performance penalty.
David Rodríguez - dribeas
Warning: Function local statics (like str_quux in your example) are not initialized at program startup, but on the first execution of the containing function. This causes thread safety issues.
Éric Malenfant
+1  A: 

TBH its probably best to ONLY construct error messages when they are needed (ie if something goes badly wrong who cares if you get a slowdown). If the messages are always going to appear then its probably best to define them statically to avoid the fact that they will be initialised each time. Generally, though, I only display user messages in debug mode so its quite easy to not show them if you are trying to do a performance build. I then only construct them when they are needed.

Goz
+1 Defining Variables at the top of a function is (rightly, IMO) frowned upon in C++. Define them when they are needed. (And if you don't intent to manipulate the messages, why create the strings at all?)
sbi