开发者

c++ main() brain teaser

开发者 https://www.devze.com 2023-02-28 15:35 出处:网络
Can you think of a situ开发者_如何学Goation where your program would crash without reaching the breakpoint which you set at the beginning of main()?

Can you think of a situ开发者_如何学Goation where your program would crash without reaching the breakpoint which you set at the beginning of main()?

My answer is during the initialization of static variables, but not sure...


THe above examples are true, but in my experience it's usually due to some problem loading a DLL...


A very simple example

struct abc
{
   abc()
   {
       int* p = 0;
       *p = 42; // Drat!
   }
};

abc obj;
int main(){}


My answer gives 100% guarantee that this will crash before main().

#include <exception>

struct A
{
   A() 
   {
       std::terminate(); //from <exception>
       //you can also call std::abort() from <cstdlib>
   }
};
A a;

int main(){}

Demo : http://www.ideone.com/JIhcz


Another solution:

struct A
{
   A() 
   {
       throw "none";
   }
};
A a;

int main(){}

Demo : http://www.ideone.com/daaMe

0

精彩评论

暂无评论...
验证码 换一张
取 消