views:

452

answers:

4

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.

+4  A: 

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.

Charlie Martin
+3  A: 

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.

Judge Maygarden
+2  A: 

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

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

Joshua
A: 

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.

GiM