Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ allocation on the stack acting curiously

Curious things with g++ (maybe 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;
        }
}

Compied with g++:

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

The first type of allocation does not construct the object. What am I missing?

like image 525
moala Avatar asked Feb 18 '10 23:02

moala


3 Answers

The first type of construction is not actually constructing the object. In order to create an object on the stack using the default constructor, you must omit the ()'s

Object myObjectOnTheStack;

Your current style of definition instead declares a function named myObjectOnTheStack which returns an Object.

like image 80
JaredPar Avatar answered Nov 09 '22 13:11

JaredPar


Yet another example of the "most vexing parse". Instead of defining an object, you've declared a function named myObjectOnTheStack that takes no arguments and returns an Object.

like image 27
Jerry Coffin Avatar answered Nov 09 '22 13:11

Jerry Coffin


Object myObjectOnTheStack();

is a forward declaration of a function myObjectOnTheStack taking no parameters and returning an Object.

What you want is

Object myObjectOnTheStack;
like image 2
johannes Avatar answered Nov 09 '22 13:11

johannes