巴扎黑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.
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
天蓬老师2017-04-17 15:31:27
The return value type of theWhy are the addresses different?
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();