How to return myclass reference?



  • i trying this, but i have issues 'reference to local variable temp returned'. I know this question not about Qt.

    Contact& GlobalAll::getContactByUID(const int &UID) {
        int low = 0, high = this->allContacts.size() - 1;
    
        while (low <= high) {
            int middle = (low + high) >> 1;
    
            if (this->allContacts[middle].UID == UID) {
                Contact &now = this->AllContacts[middle];
                return now;
            }
    
            if (this->allContacts[middle].UID < UID) {
                low = middle + 1;
            } else {
                high = middle - 1;
            }
        }
    
        Contact temp;
    
        return temp;
    }
    


  • Hi!

    Contact& GlobalAll::getContactByUID(...) { // returns a reference to a Contact object
       // ...
        Contact temp; // local object that lives on the stack
        return temp; // takes address of the local object and returns it
    } // temp goes out of scope and gets destroyed, thus the reference points to invalid memory
    


  • @Wieland Yes I know a little about it.
    When I call this function, it does not come to temp, that means the object will always come back. I just want this issue disappear.



  • You can't: to return a reference the returned object must exist outside the function scope. To "solve" the issue you must either change the signature to Contact GloballAll::getContactByUID() or to something like bool GloballAll::getContactByUID( ..., Contact& return )



  • @JohanSolo thank for the answer. solved.


  • Qt Champions 2017

    Just FYI, there's a rather obscure and bad (in my opinion) feature of the language concerning returning references to local objects. You are allowed to return const references to local objects causing the lifetime of the the object to be extended beyond the usual one, and to be bound to the life time of the const reference itself.

    Here's a longer discussion about it:
    https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/



  • My suggestion: return a pointer instead of a reference:

    Contact* GlobalAll::getContactByUID(const int &UID) {
        int low = 0, high = this->allContacts.size() - 1;
    
        while (low <= high) {
            int middle = (low + high) >> 1;
    
            if (this->allContacts[middle].UID == UID) {
                return &(this->AllContacts[middle]);
            }
    
            if (this->allContacts[middle].UID < UID) {
                low = middle + 1;
            } else {
                high = middle - 1;
            }
        }
        return nullptr;
    }
    


  • @VRonin said in How to return myclass reference?:

    Contact* GlobalAll::getContactByUID(const int &UID) {

    Actually I don't see why that is any better than returning nothing at all, void GlobalAll::getContactByUID(const int &UID) { ...



  • This post is deleted!


  • @Wieland I think this is a search function so it must return a "reference" to the object with contact.UID==UID or null if it can't find the item.

    P.S.
    If you find yourself using this function a lot, consider changing allContacts into a QHash<int,Contact> and use the UID as key



  • @VRonin said in How to return myclass reference?:

    or null if it can't find the item.

    No. Contact will be in my QList.

    @VRonin said in How to return myclass reference?:

    If you find yourself using this function a lot, consider changing allContacts into a QHash<int,Contact> and use the UID as key

    I do not know about QHash <T, T>, It's faster than a binary search?
    If my allContacts.size() == 10 000, 15 Checks i need maximum.


  • Moderators



  • @jsulm @VRonin Thank guys.
    Also there are good example http://developers-club.com/posts/170017/

    @VRonin said in How to return myclass reference?:

    If you find yourself using this function a lot, consider changing allContacts into a QHash<int,Contact> and use the UID as key

    I think you are right. Thank.
    how much seconds will be lost if I search an element in QList one milion times(if i use binary search) and how much will be reserved in QHash?


  • Moderators

    @Taz742 said in How to return myclass reference?:

    how much seconds will be lost if I search an element in QList one milion times and how much will be reserved in QHash?

    Searching in a list is O(n). Statistically you will need n/2 comparisons to find what you're looking for. Hash is O(1) - so much faster. For lookup you should use QHash or QMap not QList.

    You you want to see the difference then just write a small app and measure the time...


  • Qt Champions 2017

    @Taz742 said in How to return myclass reference?:

    how much seconds will be lost if I search an element in QList one milion times(if i use binary search) and how much will be reserved in QHash?

    Algorithmic complexity isn't measured in seconds, but with the so called "big O notation" (asymptotic complexity). Provided you can do a binary search, which implies the list is kept at all times ordered, then the complexity of the search is O(logN). For a hash it's O(1) with worst-case O(N). Now, there are nuances, but most of the time a hash would fare better than a red-black tree (QMap), which would be better than keeping an ordered list and doing a binary search on it. Of course the best is to have everything in a vector and just get the elements by index, but that's not always possible.



    • Simple code is better than complex code.
    • Only sacrifice simplicity if you have proof that your code is too slow.
    • The only way to prove that your code is too slow is by measuring execution time against real world data on the target machine.
    • Don't just assume that algorithmic complexity dominates execution time; you have to measure it.

    Just my 2 cents.



    • Avoid premature pessimization - by default use data structures and algorithms which are right for the job, without sacrificing simplicity.

    Otherwise you may get a death of thousand cuts for performance of your application, when it's not enough to fix a few bottlenecks because all code if uniformly slow.



  • Pleasant discussion.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.