C++ 公有方法返回vector与私有vector不是同一个
黄舟
黄舟 2017-04-17 15:29:27
0
3
856
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
巴扎黑

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

左手右手慢动作

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

Peter_Zhu

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();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template