Home  >  Q&A  >  body text

C++ 公有方法返回vector与私有vector不是同一个

黄舟黄舟2714 days ago739

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 15:31:27

    Of course the returned vector value is not the same address, the returned one has been copied.
    Can return pointers and const pointers.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 15:31:27

    The value returned by

    is of course copied. If you don’t believe it, you can change the return value of GetcomputerFishes and see if the data of this->computerFishes is consistent

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 15:31:27

    Why are the addresses different?

    The return value type of the

    GetcomputerFishes function is vector<ComputerFish *>, that is, returned by value; at the same time, the expression in the return statement is computerFishes, so here a temporary object will be copied and constructed first, and then the temporary object will be returned ( Note: Due to Copy elision, this temporary object may not actually be copied and constructed during actual runtime). That is, the returned object is not a member variable of MyClass, but a temporary object constructed by copying this member variable, so their addresses are different. (Note: The expression type when calling by value is an rvalue. User code cannot directly get the address of the return value, that is, it cannot &x.GetcomputerFishes(). But it can be converted into an lvalue and then get the address.)

    How to make the object returned by GetcomputerFishes be computerFishes?

    If you want this function to return the private member computerFishes of MyClass, you can use return by reference.

    vector<ComputerFish *> &GetcomputerFishes() { return computerFishes; }
    const vector<ComputerFish *> &GetcomputerFishes() const { return computerFishes; }
    

    This set of function overloads provide support for const MyClass objects and non-const MyClass objects respectively.

    Then you can use the return value to initialize the reference variable (you can also initialize the non-reference variable, copy initialization):

    vector<ComputerFish *> &ref = x.GetcomputerFished();
    ref.clear();
    

    Of course, it can also be accessed directly through the function return value:

    x.GetcomputerFished().clear();
    

    reply
    0
  • Cancelreply