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

空扰寡人 提交于 2019-12-04 16:41:50

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.

Judge Maygarden

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.

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!