Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c++ - How to catch exception thrown while initializing a static member

I have a class with a static member:

class MyClass
{
public:
    static const SomeOtherClass myVariable;
};

Which I initialize in the CPP file like so:

const SomeOtherClass MyClass::myVariable(SomeFunction());

The problem is, SomeFunction() reads a value from the registry. If that registry key doesn't exist, it throws an exception. This causes my program to explode without giving the user any useful output... is there some way I can catch the exception so I can log it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't like static data members much, the problem of initialization being foremost.

Whenever I have to do significant processing, I cheat and use a local static instead:

class MyClass
{
public:
    static const SomeOtherClass& myVariable();
};

const SomeOtherClass& MyClass::myVariable()
{
  static const SomeOtherClass MyVariable(someOtherFunction());
  return MyVariable;
}

This way, the exception will be throw only on first use, and yet the object will be const.

This is quite a powerful idiom to delay execution. It had a little overhead (basically the compiler checks a flag each time it enters the method), but better worry about correctness first ;)

If this is called from multiple threads:

  • if your compiler handles it, fine
  • if your compiler does not, you may be able to use local thread storage (it's const anyway)
  • you could use boost::once in the Boost.Threads library
  • since it's const, you may not care if it's initialized multiple times, unless someOtherFunction does not support parallel execution (beware of resources)

Guideline: only use static or global variables instantiation for simple objects (that cannot throw), otherwise use local static variables to delay execution until you can catch the resulting exceptions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...