Unique_ptr object is destroyed.

Hi there

I have wired situation with my object I have created object with unique_ptr, however I wanted to full prof a bit and if someone select book that was already rented it should get message This book is already borrowed!
but when I added if else statement my object is being destroyed. If I comment it out (if/else) it will work fine.

it appears I am destroying object just by reading it. why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
case '3': {
                std::cout << "Please select book to borrow: ";
                lib.Print();
                unsigned int book_selection = 0;
                std::cin >> book_selection;
                if (lib.Borrow(book_selection) != nullptr)
                {
                    std::unique_ptr<Book> borrow_book_ptr = lib.Borrow(book_selection);
                    person.Borrow(std::move(borrow_book_ptr));
                } else{
                    std::cout << "This book is already borrowed!\n";
                }
                std::system("clear");
                break;
Maybe use some non-destructive function to test whether the book is in the library.

Instead of
 
    if (lib.Borrow(book_selection) != nullptr)
Perhaps try something like:
 
    if ( lib.available(book_selection) )


Where the function is declared as const so it cannot modify the object, maybe like this:
1
2
3
4
5
    
    bool available  (unsigned int book_selection) const
    {
        return (shelf_with_books.at(book_selection) != nullptr);
    }
Chervil that is one awesome suggestion!! :)
i was surprised that checking in such way would destroy object as this is only reading not changing it!

thank you :)

and it works nicely :) thank you
Last edited on
i was surprised that checking in such way would destroy object as this is only reading not changing it!


Well, the function Borrow uses std::move which just might change something:
1
2
3
4
   std::unique_ptr<Book> Borrow(unsigned int book_selection)
    {
        return std::move(shelf_with_books.at(book_selection));
    }
true, true. but in such case I was expecting (hoping maybe is better word) throw an error. well I am learning new stuff everyday :)

thank you
Using unique pointers can sometimes cause that kind of errors and it's important to detect and solve them as quick as possible as they mistake get harder to find. There are external tools you can use in order to do it, such as checkamrx that works pretty good.
Goosd luck.
Topic archived. No new replies allowed.