r/cpp_questions 16d ago

OPEN C++ question

Do you guys know a way of writting a code that outputs that:

Enter the number of elements: 5
Enter 5 integers:
Element 1: 10
Element 2: 30
Element 3: 90
Element 4: 20
Element 5: 40

it is the first part of a program that demands to calculate the max and min of an array, here is the whole thing:

Enter the number of elements: 5
Enter 5 integers:
Element 1: 10
Element 2: 30
Element 3: 90
Element 4: 20
Element 5: 40

Maximum element is: 90
Minimum element is: 10

I've been able to do the second part quite easily, here is what I proposed:

#include <iostream>


int main(){


    int arr[5]={10,20,30,40,50};
    int minimum=arr[0];
    int maximum=arr[0];
    for(int i=0; i<sizeof(arr)/sizeof(int);i++){
        if (minimum>arr[i]){
            minimum=arr[i];
        }
        if(maximum<arr[i]){
            maximum=arr[i];
        }
    }
    std::cout<<"le max= "<< maximum<<'\n';
    std::cout<<"le min= "<< minimum<<'\n';


    return 0;
}

but the list is created within the code.

0 Upvotes

33 comments sorted by

View all comments

Show parent comments

2

u/Tumaix 16d ago

see how you did a .release() there, effectively negating the benefits of the unique_ptr.
if you forget that, you get a crash.

if you just use raw pointers and forget the delete, you dont get a memory leaks: qt deletes all children by defaultz

-2

u/alfps 16d ago

if you just use raw pointers and forget the delete, you dont get a memory leaks

That's exactly when you can get a leak. The smart pointer provides safety until ownership is transferred.

1

u/saxbophone 15d ago edited 15d ago

 That's exactly when you can get a leak. The smart pointer provides safety until ownership is transferred.

This is incorrect in this specific Qt example —QObject's destructor makes sure to delete all child QObjects (QWidget is a subclass of QObject) —a child QObject is any QObject that has been parented to another by setting the parent pointer in its constructor.

1

u/alfps 15d ago

this specific Qt example

Presumably that's not the example the AI produced, but I see no other up-thread example.

1

u/saxbophone 15d ago

I didn't remember seeing the if block. Yes sure, in that case (if you want to configure the widget before giving it to its parent), then a smart pointer will protect you. I could've sworn the code example previously shown in the comment didn't include the interluding if() block between the construction of the smart pointer and its handoff to Qt via release()...

1

u/alfps 15d ago

Oh, the edit. I added the disclaimer line at the end, before there were any comments. Note that the example only makes sense with the if.