For example this class:
class RTPIPv4Address{
public:
RTPIPv4Address(int a, int b);
}
Silly question but... I just stumbled on code which initialized a class instance like that with for example
RTPIPv4Address adr(2,2);
Now I am wondering, is this just another syntax for the usual
RTPIPv4Address* adr = new RTPIPv4Address (2,2);
or does it have any ot开发者_JAVA百科her effects? For example, given the lack of a pointer and a new(), is it declared on the stack like other local variables do and then get deallocated at function return or is it saved on the heap and therefore persist?
Thanks in advance
Yes, the first example is stack-allocated and will have it's destructor called and be deallocated as soon as the variable loses scope. For a local variable, this usually happens when the function returns, though you can force it to lose scope earlier with curly braces.
function
{
RTPIPv4Address adr(2,2);
return; //adr loses scope and destructor is called
}
That's how it's normally allocated on the stack and where it loses scope, but it can happen other places as well.
function
{
if (condition)
{
RTPIPv4Address adr(2, 2);
//do stuff with adr
} //adr loses scope and destructor is called
//do more stuff
return;
}
The two both construct an object but apart from that are very dissimilar. The first constructs on the stack, the second on the heap. The first form should be used wherever possible. The second form should be used if and only if you need the object to persist, or, it is too large to fit on the stack. new
is not the "usual" form of object creation at all in C++.
The first example will stack-allocate your object. The only way to get something on the heap is via new
(and, obviously, malloc
or other low-level operations like mmap
).
精彩评论