我来自Java背景,已经开始使用C++中的对象。但我想到的一件事是,人们经常使用指向对象的指针,而不是对象本身,例如这样的声明:

Object *myObject = new Object;

而不是:

Object myObject;

或者不用函数,让我们说testFunc(),如下所示:

myObject.testFunc();

我们必须写下:

myObject->testFunc();

但我不明白我们为什么要这样做。我认为这与效率和速度有关,因为我们可以直接访问内存地址。我说得对吗?


当前回答

我将包括指针的一个重要用例。当您在基类中存储一些对象时,但它可能是多态的。

Class Base1 {
};

Class Derived1 : public Base1 {
};


Class Base2 {
  Base *bObj;
  virtual void createMemerObects() = 0;
};

Class Derived2 {
  virtual void createMemerObects() {
    bObj = new Derived1();
  }
};

因此,在这种情况下,不能将bObj声明为直接对象,必须有指针。

其他回答

指针有很多用例。

多态行为。对于多态类型,指针(或引用)用于避免切片:

class Base { ... };
class Derived : public Base { ... };

void fun(Base b) { ... }
void gun(Base* b) { ... }
void hun(Base& b) { ... }

Derived d;
fun(d);    // oops, all Derived parts silently "sliced" off
gun(&d);   // OK, a Derived object IS-A Base object
hun(d);    // also OK, reference also doesn't slice

引用语义和避免复制。对于非多态类型,指针(或引用)将避免复制可能昂贵的对象

Base b;
fun(b);  // copies b, potentially expensive 
gun(&b); // takes a pointer to b, no copying
hun(b);  // regular syntax, behaves as a pointer

注意,C++11具有移动语义,可以避免将昂贵的对象复制到函数参数中并作为返回值。但是使用一个指针肯定会避免这些问题,并且允许在同一个对象上使用多个指针(而一个对象只能从一次移动)。

资源获取。在现代C++中,使用新运算符创建指向资源的指针是一种反模式。使用特殊的资源类(标准容器之一)或智能指针(std::unique_ptr<>或std::shared_ptr<>)。考虑:

{
    auto b = new Base;
    ...       // oops, if an exception is thrown, destructor not called!
    delete b;
}

vs.

{
    auto b = std::make_unique<Base>();
    ...       // OK, now exception safe
}

原始指针只能用作“视图”,而不能以任何方式涉及所有权,无论是通过直接创建还是通过返回值隐式创建。另请参阅C++常见问题解答中的问答。

更细粒度的生命周期控制每次复制共享指针(例如作为函数参数)时,它指向的资源都保持活动状态。常规对象(不是由new创建的,直接由您创建或在资源类中创建)在超出范围时被销毁。

这已经详细讨论过了,但在Java中,一切都是指针。它不区分堆栈和堆分配(所有对象都在堆上分配),因此您不会意识到您正在使用指针。在C++中,可以根据内存需求将两者混合使用。C++中的性能和内存使用更具确定性(duh)。

C++提供了三种传递对象的方法:通过指针、引用和值。Java限制您使用后一种类型(唯一的例外是int、boolean等原始类型)。如果你想使用C++而不仅仅是一个奇怪的玩具,那么你最好了解这三种方式之间的区别。

Java假装不存在“谁和什么时候应该销毁这个?”这样的问题。答案是:《垃圾收集器》,棒极了。然而,它不能提供100%的内存泄漏保护(是的,java可以泄漏内存)。实际上,GC给你一种错误的安全感。你的SUV越大,离撤离者的距离就越长。

C++让您面对面地了解对象的生命周期管理。好吧,有一些方法可以解决这个问题(智能指针家族、Qt中的QObject等等),但它们都不能像GC那样以“火即忘”的方式使用:您应该始终记住内存处理。你不仅应该关心破坏一个物体,还必须避免多次破坏同一个物体。

还不害怕吗?好的:循环引用——你自己处理,人类。记住:每一个对象都要被精确地杀死一次,我们C++运行时不喜欢那些处理尸体的人,只留下死去的人。

所以,回到你的问题。

当您通过值(而不是指针或引用)传递对象时,每次执行“=”操作时,都会复制对象(整个对象,无论是几个字节还是一个巨大的数据库转储-您足够聪明,可以避免后者,不是吗?)。要访问对象的成员,请使用“”(点)。

当通过指针传递对象时,只复制几个字节(32位系统为4个,64位系统为8个),即该对象的地址。为了向所有人展示这一点,当您访问成员时,可以使用这个花哨的“->”运算符。或者可以使用“*”和“.”的组合。

当你使用引用时,你会得到一个伪装成值的指针。这是一个指针,但您可以通过“.”访问成员。

还有,再一次让你大跌眼镜:当你声明几个用逗号分隔的变量时,然后(注意指针):

每个人都有类型值/指针/引用修饰符是单独的

例子:

struct MyStruct
{
    int* someIntPointer, someInt; //here comes the surprise
    MyStruct *somePointer;
    MyStruct &someReference;
};

MyStruct s1; //we allocated an object on stack, not in heap

s1.someInt = 1; //someInt is of type 'int', not 'int*' - value/pointer modifier is individual
s1.someIntPointer = &s1.someInt;
*s1.someIntPointer = 2; //now s1.someInt has value '2'
s1.somePointer = &s1;
s1.someReference = s1; //note there is no '&' operator: reference tries to look like value
s1.somePointer->someInt = 3; //now s1.someInt has value '3'
*(s1.somePointer).someInt = 3; //same as above line
*s1.somePointer->someIntPointer = 4; //now s1.someInt has value '4'

s1.someReference.someInt = 5; //now s1.someInt has value '5'
                              //although someReference is not value, it's members are accessed through '.'

MyStruct s2 = s1; //'NO WAY' the compiler will say. Go define your '=' operator and come back.

//OK, assume we have '=' defined in MyStruct

s2.someInt = 0; //s2.someInt == 0, but s1.someInt is still 5 - it's two completely different objects, not the references to the same one

在内存利用率很高的领域,指针很方便。例如,考虑一个极大极小算法,其中将使用递归例程生成数千个节点,然后使用它们来评估游戏中的下一个最佳移动,解除分配或重置(如智能指针)的能力显著减少了内存消耗。而非指针变量继续占用空间,直到其递归调用返回值。

这个问题有很多很好的答案,包括前向声明、多态性等重要用例,但我觉得你的问题的“灵魂”部分没有得到回答,即Java和C++中不同的语法意味着什么。

让我们来比较一下这两种语言的情况:

Java语言:

Object object1 = new Object(); //A new object is allocated by Java
Object object2 = new Object(); //Another new object is allocated by Java

object1 = object2; 
//object1 now points to the object originally allocated for object2
//The object originally allocated for object1 is now "dead" - nothing points to it, so it
//will be reclaimed by the Garbage Collector.
//If either object1 or object2 is changed, the change will be reflected to the other

与此最接近的等效值为:

C++:

Object * object1 = new Object(); //A new object is allocated on the heap
Object * object2 = new Object(); //Another new object is allocated on the heap
delete object1;
//Since C++ does not have a garbage collector, if we don't do that, the next line would 
//cause a "memory leak", i.e. a piece of claimed memory that the app cannot use 
//and that we have no way to reclaim...

object1 = object2; //Same as Java, object1 points to object2.

让我们看看另一种C++方式:

Object object1; //A new object is allocated on the STACK
Object object2; //Another new object is allocated on the STACK
object1 = object2;//!!!! This is different! The CONTENTS of object2 are COPIED onto object1,
//using the "copy assignment operator", the definition of operator =.
//But, the two objects are still different. Change one, the other remains unchanged.
//Also, the objects get automatically destroyed once the function returns...

最好的方法是——或多或少——Java(隐式)处理指向对象的指针,而C++可以处理指向对象或对象本身的指针。这是有例外的——例如,如果您声明Java“原始”类型,它们是复制的实际值,而不是指针。所以

Java语言:

int object1; //An integer is allocated on the stack.
int object2; //Another integer is allocated on the stack.
object1 = object2; //The value of object2 is copied to object1.

也就是说,使用指针不一定是正确或错误的处理方式;然而,其他答案已经令人满意地涵盖了这一点。不过,总的想法是,在C++中,您可以对对象的生存期以及它们将生存的位置进行更多的控制。

重点是——Object*Object=newObject()构造实际上最接近典型的Java(或C#)语义。