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

2020-07-25 10:37发布

问题:

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.

回答1:

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.



回答2:

You can create an "anonymous" automatic variable, but not a static one. The following would create an object of class A and call the constructor and then call the destructor on function exit.

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

You could get a similar effect by allocating the object on the heap or constructing it in place in a preallocated location.

void foo()
{
    new A();
}

void foo()
{
    static char memory[sizeof (A)];
    new (memory) A();
}

However, in both cases the object cannot be cleaned up correctly since a pointer is not held for a later call to delete. Even though the static memory will be released the destructor will never be called. Anonymous objects only really make since when used with a garbage collector.



回答3:

Somehow, I think this guy's after a singleton constructor side effect.

Anyway, just give the darn thing a variable name already.



回答4:

Of course there are anonymous objects in C++ ! A(100) is anonymous object in this sample

However if you think about it, it makes no sense to create static anonymous object.