C ++ distribution on the stack, curious

Interesting things with g ++ (perhaps also with other compilers?):

struct Object {
        Object() { std::cout << "hey "; }
        ~Object() { std::cout << "hoy!" << std::endl; }
};

int main(int argc, char* argv[])
{
        {
                Object myObjectOnTheStack();
        }
        std::cout << "===========" << std::endl;
        {
                Object();
        }
        std::cout << "===========" << std::endl;
        {
                Object* object = new Object();
                delete object;
        }
}

Corresponding to g ++:

===========
hey hoy!
===========
hey hoy!

The first type of selection does not create an object . What am I missing?

+5
source share
3 answers

The first type of construction does not actually create an object. To create an object on the stack using the default constructor, you must omit()

Object myObjectOnTheStack;

Your current definition style instead declares a function called myObjectOnTheStack, which returns Object.

+12
source

" ". myObjectOnTheStack, Object.

+4
Object myObjectOnTheStack();

- This is a direct declaration of the function myObjectOnTheStackwithout parameters and return Object.

Do you want to

Object myObjectOnTheStack;
+2
source

All Articles