search

Home  >  Q&A  >  body text

话说在C++中,什么时候用指针?什么时候直接用变量?

感觉我平时能用指针都用指针的说……

迷茫迷茫2767 days ago715

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 11:33:24

    If you don’t need pointers, don’t use pointers. Smart pointers and references are both good choices.

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:33:24

    I feel that not using pointers in C++ is equivalent to breaking the wings of C++, but you need to be very careful when using pointers.

    Basically speaking, where is new, delete is there (a special case is that new is in the create() method and delete is in the remove() method, but both create() and remove() need to be in the same code block as much as possible. , and so on, the most typical ones are new in construction and delete in destruction.

    In addition, try not to use pointer arithmetic. If operations are required, use data processing as much as possible. For example, *(p++) can be written as p[1], so as to avoid changing the value of the pointer and causing confusion.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 11:33:24

    If you are sure that you can control the life cycle of the object using pointers, then you can use pointers. (Note that C++ exceptions should be taken into account)
    Otherwise, use smart pointers.

    reply
    0
  • Cancelreply