What is difference between instantiating an object using new vs. without
In C++,
Aside from dynamic memory allocation, is there a functional difference between the following two lines of code:
Time t (12, 0, 0); //t is a Time object
Time* t = new Time(12, 0, 0);//t is a pointer to a dynamically allocated Time object
I am assuming of course that a Time(int, int, int) ctor has been defined. I also realize that in the second case t will need to be deleted as it was allocated on the heap. Is there any other difference?
The line:
Time t (12, 0, 0);
... allocates a variable of type Time
in local scope, generally on the stack, which will be destroyed when its scope ends.
By contrast:
Time* t = new Time(12, 0, 0);
... allocates a block of memory by calling either ::operator new()
or Time::operator new()
, and subsequently calls Time::Time()
with this
set to an address within that memory block (and also returned as the result of new
), which is then stored in t
. As you know, this is generally done on the heap (by default) and requires that you delete
it later in the program, while the pointer in t
is generally stored on the stack.
另一个更明显的区别是访问t的变量和方法时。
Time t (12, 0, 0);
t.GetTime();
Time* t = new Time(12, 0, 0);
t->GetTime();
As far as the constructor is concerned, the two forms are functionally identical: they'll just cause the constructor to be called on a newly allocated object instance. You already seem to have a good grasp on the differences in terms of allocation modes and object lifetimes.
链接地址: http://www.djcxy.com/p/78542.html