[英]Why do we need a pointer to a class if we can instantiate an object of it and access members of the class?
I am a little confused here. 我在这里有点困惑。 If we can instantiate an object of a class and access member methods then why a pointer to a class?
如果我们可以实例化一个类的对象并访问成员方法那么为什么指向一个类的指针? Is there any benefit to it?
它有什么好处吗? And when do we use a pointer to a class and when do we instantiate an object of it?
我们何时使用指向类的指针,何时实例化它的对象?
Thank you. 谢谢。
You might not need a pointer to a class. 您可能不需要指向类的指针。 If your class is small, doesn't exhibit polymorphic behavior through a base class, or cost anything to instantiate, you can probably just rip one off on-the-fly and be done.
如果你的类很小,没有通过基类表现出多态行为,或者需要花费任何实例化的东西,你可能只需要动态地删除一个并完成。
But in many cases, we need pointers because: 但在许多情况下,我们需要指针,因为:
If we can instantiate an object of a class and access member methods then why a pointer to a class?
如果我们可以实例化一个类的对象并访问成员方法那么为什么指向一个类的指针?
If you have just a base class and no derived classes, then it is good to create the object on the stack rather than pointer to the class. 如果你只有一个基类而没有派生类,那么最好在堆栈上创建对象而不是指向类的指针。 In the latter, you should be calling
delete
on the pointer to return the resources acquired by new
. 在后者中,您应该在指针上调用
delete
来返回new
获取的资源。 (Also make sure that stack never overflows. If you need large number of array of instances, then instantiate using new
is the only option.) (还要确保堆栈永远不会溢出。如果需要大量的实例数组,那么使用
new
实例化是唯一的选择。)
class foo
{
int a ;
};
foo obj1 ;
foo obj2 = obj1 ; // Copy construction. Both obj2, obj1 have it's independent
// copy of objects. (Deep copy)
foo *obj3 = new foo ;
foo *obj4 = obj3 ; // Copy construction. However, both obj3, obj4 point to the
// same object. (Shallow copy)
// You should be careful in this case because deletion of obj3
// makes obj4 dangling and vice versa.
Is there any benefit to it?
它有什么好处吗?
Polymorphism because it works only for pointers / references. 多态性因为它仅适用于指针/引用。
And when do we use a pointer to a class and when do we instantiate an object of it?
我们何时使用指向类的指针,何时实例化它的对象?
It depends on the requirement. 这取决于要求。 As said earlier, if you have just a base class creation of object on stack is a better option.
如前所述,如果你只有一个基类创建堆栈上的对象是一个更好的选择。
One reason might be performance. 一个原因可能是表现。 Imagine you have 100 instances of some class.
想象一下,你有一些类的100个实例。 If you are not using pointers and you want to do something like copy those instances from one container to another, there is quite a bit of overhead as the copy constructor would need to be called on each one.
如果你没有使用指针而你想要做一些事情,比如将这些实例从一个容器复制到另一个容器,那么由于需要在每个容器上调用复制构造函数,所以会产生相当大的开销。 However, if you had pointers to those instances instead then the only thing really being copied is the pointer making the operation much much quicker.
但是,如果你有指向那些实例的指针,那么唯一真正被复制的是指针使操作更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.