Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: avoid optimizing out variable

Tags:

c++

I have some useful code in constructor or class Valuable. I want be sure it's executed before submain. How can I guarantee that it's not optimized out?

int main()
{
    // Dear compiler, please don't optimize ctor call out!
    Valuable var;

    return submain();
}

Is local variable enough? Do I need to use static:

static Valuable *v = new Valuable();
delete v;
v = NULL;

Can I shorten previous to one liner:

delete new Valuable();
like image 627
demi Avatar asked Feb 05 '26 20:02

demi


1 Answers

If your constructor or destructor has observable behavior, the compiler is not allowed to optimize it out. So there's no need to do anything tricky.

like image 177
Adam Rosenfield Avatar answered Feb 09 '26 04:02

Adam Rosenfield