Why don't you return the reference?

Asked 2 years ago, Updated 2 years ago, 154 views

Why can't I return the reference?

Personally, I saw a lot of codes that return references, so are all the codes wrong?

c++ reference

2022-09-22 22:25

1 Answers

Are you talking about this?

int& getInt(void)
{
    int i;
    return i;
}

If the reference is returned, If you do not process the reference separately, it is recommended not to return the reference because the reference remains in the stack. If you look at the following code together,

int& getInt(void)
{
    int *i = new int;
    return *i;
}

For both codes int& myInt = getInt(); // & is specified int badInt = getInt(); // & missing delete&myInt; // delete can be done delete&badInt; // badInt copies int assigned to the stack, but there is no way to delete

Because that's it.

I think the best way to return a pointer or reference is

int *getInt(void)
{
    return new int;
}

It's written with. If you receive the return,

int *myInt = getInt(); // Returned as pointer type int& weirdInt = *getInt(); // This can also be used delete myInt; // It's a pointer, so of course delete is possible delete&weirdInt; // This is also possible


2022-09-22 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.