Sam
Sam

Reputation: 1327

Update the value of object reference

I have a function as below. I tried to change the value of object reference to a new object by using dir = Directory(path); but I got a compilation error as below. Any advice? Also is this a good way to do this?

Error C2280 'Directory &Directory::operator =(const Directory &)': attempting to reference a deleted function

class Directory
{
public:
    const fs::path path;
    Directory *parent;
    std::vector<Directory *> sub_dir;
    std::vector<File *> files;

    Directory(const fs::path path, Directory *parent = NULL);
    double const deltaBase = .001;

    Directory(const Directory&) = default;
    Directory& operator=(const Directory&) = default;

    std::string getDirName(void);
};

void create_imgui_window(ImGui::FileBrowser *fileDialog, const char *label, char path[MAX_PATH_LENGTH], Directory &dir)
{
    // (optional) set browser properties
    fileDialog->SetTitle("Browse");

    ImGui::Begin(label);
    IMGUI_LEFT_LABEL(ImGui::InputText, "Path", path, MAX_PATH_LENGTH);
    if (ImGui::IsItemHovered() && path[0])
        ImGui::SetTooltip(path);
    ImGui::SameLine();
    if (ImGui::Button("Browse"))
        fileDialog->Open();

    create_directory_tree(dir);

    ImGui::End();

    fileDialog->Display();

    if (fileDialog->HasSelected())
    {
        strcpy_s(path, MAX_PATH_LENGTH, fileDialog->GetSelected().string().c_str());
        std::cout << "Selected directory: " << path << std::endl;
    
        dir = Directory(path);

        fileDialog->ClearSelected();
    }
}

Final Answer: Remove the const on fs::path path;

class Directory
{
public:
    fs::path path;
    Directory *parent;
    std::vector<Directory *> sub_dir;
    std::vector<File *> files;

    Directory(const fs::path path, Directory *parent = NULL);

    Directory& operator=(const Directory&) = default;

    std::string getDirName(void);
};

Upvotes: 0

Views: 92

Answers (1)

rawrex
rawrex

Reputation: 4064

You ask your copy-assignment operator to be implicitly defined:

Directory& operator=(const Directory&) = default;

Meanwhile you have const data members:

const fs::path path; // Consider omitting the const here
const double deltaBase = .001; // Seems like a candidate for a static member

The synthesized (implicitly defined) copy-assignment operator defined as deleted if a class has a data member that is const or a reference (or if the class has a data member that has a deleted or inaccessible copy-assignment operator on its own).

Consider two approaches:

  • The non-const path data member, as well as deltaBase not being const inside each Directory instance.
  • Making the create_imgui_window function to return a Directory, instead of modifying one.

Upvotes: 3

Related Questions