Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an anonymous object be declared static in C++?

Is this allowed? :

class A;
void foo()
{
    static A();
}

I get signal 11 when I try to do it, but the following works fine:

class A;
void foo()
{
    static A a;
}

Thank you.

like image 330
Igor Avatar asked Feb 05 '26 09:02

Igor


1 Answers

Nope. There is no such thing as an "anonymous object" in C++. There is such a thing as defining an object to type A that is immediately discarded; what you've written is an expression that returns an A object that's never assigned to a variable, like the return code of printf usually is never assigned or used.

In that code, if it worked, you'd be declaring "no object" to be allocated outside the heap. Since there's no object to allocate, it's meaningless.

like image 135
Charlie Martin Avatar answered Feb 07 '26 23:02

Charlie Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!