Why does object have a pointer and not an int?

If we type

MyObject *obj = [[MyObject alloc] init];

"obj" is a pointer to the memory address.

...When we create an int, we type:

int x = 10; 

Why don't we type?

int *x = 10; 

The question is, why do we need a pointer to object and not int, float, etc...


Efficiency.

Moving an int from one place to another is easy. Moving an object needs a little bit more work from the CPU. Moving the address of an object is as easy as moving an int.

In plain C, it is common to handle pointers to structs for the same reason. C makes it easy with the -> operator.


There are languages where you can create objects “without a pointer”, on the stack. C++, for example. One great thing about having objects on the stack is that they get automatically deallocated when the scope ends, which helps with memory management. It's also faster.

One bad thing about having objects on the stack is that they get automatically deallocated when the scope ends and the stack disappears. And since objects are usually longer-lived than local variables, you would have to copy the object's memory somewhere. It's entirely possible, but it complicates matters.

And it's not just the memory lifecycle that's complicated with stack-based objects. Consider assignment, foo = bar for two object types. If the objects are always pointers ( Class* ), you just assigned a pointer and got two pointers to the same objects; easy. If foo is stack-based ( Class ), the assignment semantics starts to get blurry – you could well end with a copy of the original object.

Introducing a rule that all objects are allocated on the heap (“with pointers”) is a great simplification. And as it happens, the speed difference doesn't matter that much, and the compiler can now also automatically insert code to deallocate heap-based objects after they go out of scope, so it's generally a win-win situation.


You can have pointer for int, float as well.

Objects are created on heap. To access it, you need the address. Thats why they are of pointer types.

链接地址: http://www.djcxy.com/p/13890.html

上一篇: 在不破坏元素的情况下调整std :: vector的大小

下一篇: 为什么对象有一个指针而不是int?