gpt4 book ai didi

c++ - 为什么有人将对象定义为指针?

转载 作者:行者123 更新时间:2023-12-01 12:18:51 25 4
gpt4 key购买 nike

我目前正在学习C++,我无法理解为什么没有明显的理由将一个类的对象定义为指针(即Car *c = new Car;而不是Car c;)?
举个例子:

#include <iostream>

class Car {
public:
void accelerate() { std::cout << "Accelerating!.\n"; }
};

int main() {
Car *c = new Car;

c->accelerate();

return 0;
}
当这样做更直观时,为什么要这样做呢?
#include <iostream>

class Car {
public:
void accelerate() { std::cout << "Accelerating!.\n"; }
};

int main() {
Car c;

c.accelerate();

return 0;
}
如果需要指向该对象的指针,则可以始终声明一个指针,不是吗?

最佳答案

why one would define an object of a class as a pointer


一个不应该。通常应尽可能避免使用指针。但是,当您进行多态时,它们是必需的。在这种情况下,请使用智能指针 shared_ptrunique_ptr代替原始指针。
以下是使用指针的错误示例,因为现在您还有另一个问题,即“释放分配的内存”。
int main() {
Car *c = new Car;
c->accelerate();
return 0;
}
没错,第二个示例要好得多,它应该是默认的处理方式。
每当出现此类问题时,最好看看 C++ Core Guidelines怎么说:

R.11: Avoid calling new and delete explicitly

Reason

The pointer returned by new should belong to a resource handle (that can call delete). If the pointer returned by new is assigned to a plain/naked pointer, the object can be leaked.


ES.60: Avoid new and delete outside resource management functions

Reason

Direct resource management in application code is error-prone and tedious.


R.3: A raw pointer (a T*) is non-owning

Reason

There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning. We want owning pointers identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.(Owning pointers are pointers which take ownership of a pointer and are responsible for freeing it.)

Example

void f()
{
int* p1 = new int{7}; // bad: raw owning pointer
auto p2 = make_unique<int>(7); // OK: the int is owned by a unique pointer
// ...
}

因此,答案是仅在绝对需要时才使用指针,否则请坚持引用和值。
什么时候使用指针?
  • 在做多态时(使用智能指针)
  • 当由于堆栈大小有限而需要一个巨大的数组(> 1MB)时。 (2 - 8 MB(usually) on linux1 MB on windows)。如果可以的话,在这种情况下,最好使用std::vector
  • 当您使用“C”库或处理旧版C++代码时,有时可能需要使用指针。
  • 关于c++ - 为什么有人将对象定义为指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63053566/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com