What does “Class* &cls” mean in C++'s function definition?

前端 未结 4 2275
后悔当初
后悔当初 2020-12-15 01:45

I know Class *cls is a pointer, and Class &cls takes the address, but what is

void fucction1( Class *&cls)

If I have Class c

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 02:35

    As said, a reference to a pointer to Class.

    • you pass a Class * to the function
    • the function may change the pointer to a different one

    This is a rather uncommon interface, you need more details to know what pointers are expected, and what you have to do with them.

    Two examples:

    Iteration

    bool GetNext(Classs *& class)
    {
       if (class == 0)  
       {
         class = someList.GetFirstObject();
         return true;
       }
    
       class = somePool.GetObjectAbove(class); // get next
       return class != 0;       
    }
    
    // Use for oterating through items:
    Class * value = 0;
    while (GetNext(value))
       Handle(value);
    

    Something completely different

    void function (Class *& obj)
    {
        if (IsFullMoon())
        {
          delete obj;
          obj = new Class(GetMoonPos());
        }
    }
    

    In that case, the pointer you pass must be new-allocated, and the pointer you receive you need to pass either to function again, or be delete'd by you.

提交回复
热议问题