Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

java - When to use pointers and when not to?

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;
}

As opposed to this:

class Foo {
    Bar* b;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Start by avoiding pointers.

Use them when:

  • 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 the Foo 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 constructing Foo).
  • In your business logic, the Bar object may not exist at all; you would use null 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.

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.

(*) any case – except, probably, the bullet regarding GUI widgets; in this case, your toolkit would most probably manage the resources for you as well


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...