何时使用指针,何时不使用? [英] When to use pointers and when not to?
问题描述
我习惯于进行 Java 编程,在编程时您从不需要真正考虑指针.但是,目前我正在用 C++ 编写程序.在创建具有其他类成员的类时,什么时候应该使用指针,什么时候不应该使用?例如,我什么时候想要这样做:
I'm used to doing Java programming, where you never really have to think about pointers when programming. However, at the moment I'm writing a program in C++. When making classes that have members of other classes, when should I use pointers and when should I not? For example, when would I want to do this:
class Foo {
Bar b;
}
与此相反:
class Foo {
Bar* b;
}
推荐答案
从避免使用指针开始.
在以下情况下使用它们:
Use them when:
- 您想使用 Pimpl idiom 或 抽象工厂.
Bar
实例实际上由程序的其他部分管理,而Foo
类只需要能够访问它.- 您想推迟
Bar
对象的构造(即,您想在构造Foo
之后 创建它). - 在您的业务逻辑中,
Bar
对象可能根本不存在;您也可以在 Java 中使用null
.但是,请查看 boost::optional 也是. Bar
实际上是一个基类,你需要实例是多态的.- 您碰巧使用的工具包更喜欢将 GUI 小部件显示为指针.示例可能包括(但当然不限于)wxWidgets 和 GLUI.
- You want to use the Pimpl idiom, or an abstract factory.
- The
Bar
instance is actually managed by some other part of your program, whereas theFoo
class just needs to be able to access it. - You want to postpone the construction of the
Bar
object (i.e., you want to create it after constructingFoo
). - In your business logic, the
Bar
object may not exist at all; you would usenull
also in Java. However, check out boost::optional as well. Bar
is actually a base class, and you need the instance to be polymorphic.- You happen to be using a toolkit that prefers to present GUI widgets as pointers. Examples could include (but are certainly not limited to) wxWidgets and GLUI.
在任何这些情况 (*) 中,首先使用智能指针,例如 boost::shared_ptr.否则,您迟早可能会忘记释放内存.一旦您知道自己在做什么,请逐案考虑哪种指针类型最好.
In any of these cases (*), start by using a smart pointer, such as boost::shared_ptr. Otherwise, you are likely to forget to deallocate the memory, sooner or later. Once you know what you are doing, consider case-by-case what pointer type is best.
(*) 任何情况——可能除了关于 GUI 小部件的项目符号;在这种情况下,您的工具包很可能也会为您管理资源
(*) any case – except, probably, the bullet regarding GUI widgets; in this case, your toolkit would most probably manage the resources for you as well
这篇关于何时使用指针,何时不使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!