Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing allocated pointer before it allocated

Tags:

c++

pointers

I'm studying the open source project ROS. While I saw the strange code.

Server server(n, "do_dishes", boost::bind(&execute, _1, &server), false);

The variable server is used before it's allocated as server. Is that possible? At least, my visual studio 2010 compiler doesn't understand that style of code. Please let me know if that is really possible code, or not.

original document of the code : http://wiki.ros.org/actionlib#C.2B-.2B-_SimpleActionServer


--------- Added

Thank you for your kindness. However I got "'server' : undeclared identifier" error when i compile it. so I tested simple code.

class TestCls {
public:
    TestCls(TestCls *aa)
    {

    }
};

int main(int argc, char **argv)
{
    TestCls tt(&tt);

}

It also makes the same error. "'tt' : undeclared identifier". am I missing something? please help me.

like image 606
Younghyo Kim Avatar asked Apr 22 '14 09:04

Younghyo Kim


People also ask

Can I free () pointers allocated with new?

No! It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program. But it is illegal, immoral, and despicable to call free() with a pointer allocated via new, or to call delete on a pointer allocated via malloc().

Are pointers dynamically allocated?

Dynamic memory allocation is to allocate memory at “run time”. Dynamically allocated memory must be referred to by pointers. the computer memory which can be accessed by the identifier (the name of the variable).

What does double * num2 do?

double *num2;Declares and initializes an pointer variable named num2.

What does pointer being freed was not allocated?

It means you're only supposed to call free on a pointer you obtained from malloc , realloc or calloc .


1 Answers

This is legal. Variables are in scope immediately when they are declared. This rule exists to enable self-referential data-structures to be constructed in a single line. The pointer can point to a non-constructed object, as long as it is not dereferenced before that object is constructed.

Since the pointer is being passed into the Server constructor, this will work, as long as Server correctly waits before calling the function object.

like image 140
Mankarse Avatar answered Sep 23 '22 19:09

Mankarse