Memory Leakage/How to use std::unique_pointer SOLVED

Hello everyone :slight_smile:
My code compiles and runs but produces an memory leak exception when closing. This is being caused by the line
FileChooser* fileChooser = new FileChooser (“Save presets to file…”, File::getCurrentWorkingDirectory(), “*.settings”);

I know that using std:unique_pointer will work but can’t find any good examples of how. Does anyone know to modify the above code to use std::unique_pointer and any resources that explain this or give an example of this?

You can use std::make_unique to initialize a unique pointer. There is a good tutorial here:

1 Like

std::unique_ptr fileChooser (new FileChooser (“Save presets to file…”, File::getCurrentWorkingDirectory(), “*.settings”));

gives me the error:

error C2059: syntax error: ‘new’


std::unique_ptr fileChooser (FileChooser (“Save presets to file…”, File::getCurrentWorkingDirectory(), “*.settings”));

gives me error:

error C2059: syntax error: ‘string’

What can I do to get the code in my first statement up top to get it to work with JUCE? Appreciate the help so far btw

Typing on a phone here, so I might get this wrong. But basically you need to declare the unique pointer like this (probably in the private section of your class):

    std::unique_ptr <FileChooser> fileChooser; 

and then initialize it in the constructor or some other function:

    fileChooser = std::make_unique<FileChooser> (my args);
1 Like

std::unique_ptr is a class template. You have to specify a template parameter when using it.

In your case:

std::unique_ptr<FileChooser> fileChooser(new FileChooser(
    "Save presets to file...",

or better, using std::make_unique (as suggested by @LiamG):

auto fileChooser = std::make_unique<FileChooser>(
    "Save presets to file...",
1 Like

It would appear you are trying to create an instance of FileChooser locally within a function. You don’t necessarily need to create it on the heap at all, assuming you do everything you need with the chooser within that function.

void MyClass::chooseFile()
  FileChooser chooser("Choose file",File(),"*.txt");
  if (chooser.browseForFileToOpen(),"*.myfile")
    // use chooser result			

You are right LiamG! This is how I will do it from now on. Doing it all in the private section outside of the constructor leads to all sorts of issues. This method right here works great. You have saved me hours!