thedarkside ofthemoon
thedarkside ofthemoon

Reputation: 2291

C++ Error with operator= of unique_ptr using std::move(nullptr)

I have seen this and I have corrected my code:

int solutionChooser = m_configFile.getChosenSolution();
ISolution* currentSolution;
switch (solutionChooser)
{
  case 1:
  {
    currentSolution = new Solution1());
    break;
  }
  case 2:
  {
    currentSolution = new Solution2());
    break;
  }
  case 3:
  {
    currentSolution = new Solution3());
    break;
  }
  case 4:
  {
    currentSolution = new Solution4());
    break;
  }
  default:
  {
    std::cout << "The specified solution does not exists\n";
    return;
  }
}

using unique_ptr as:

int solutionChooser = m_configFile.getChosenSolution();
std::unique_ptr<ISolution> currentSolution;
switch (solutionChooser)
{
  case 1:
  {
    currentSolution.reset(new Solution1());
    break;
  }
  case 2:
  {
    currentSolution.reset(new Solution2());
    break;
  }
  case 3:
  {
    currentSolution.reset(new Solution3());
    break;
  }
  case 4:
  {
    currentSolution.reset(new Solution4());
    break;
  }
  default:
  {
    currentSolution = std::move(nullptr); // here is the error
    std::cout << "The specified solution does not exists\n";
    return;
  }
}

and now I am getting the error below:

error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<ISolution>’ and ‘std::remove_reference<long int>::type {aka long int}’)

I have ISolution as interface and the SolutionX are classes derived from ISolution

How to fix this? What am I doing wrong?

Upvotes: 0

Views: 1479

Answers (3)

Marcus Ekstr&#246;m
Marcus Ekstr&#246;m

Reputation: 480

I can't add comments so I'll just post my idea about the answer.. I believe your problem is the copy constructor. The operator = is not defined with unique_ptr so instead you'll have to use a move constructor. I don't remember the correct syntax but it should be something similar to:

/* Header file */
std::unique_ptr<ISolution> currentSolution;

/* CPP file */
std::unique_ptr<ISolution> currentSolution2(new ISolution);
currentSolution = std::move(currentSolution2);

There's probably some mistakes here but hopefully it can get you to the right track. If you want a working example, I got one on floobits, user Simple2012. Link here: https://floobits.com/Simple2012/Laboration_SearchMethods Check arr.h and arr.cpp for a concrete example, however I'm using an array there instead of a class, not much difference though.

Upvotes: 0

ForEveR
ForEveR

Reputation: 55897

Your compiler is wrong, by n3376 std::unique_ptr should have following overloading

unique_ptr& operator=(nullptr_t) noexcept;

so, your code should work fine.

Upvotes: 3

BЈовић
BЈовић

Reputation: 64283

std::unique_ptr has deleted operator=, that is why you can not use it.

To reset the std::unique_ptr, use reset() method :

currentSolution.reset(nullptr);

but you do not have to do it, since the initial value is nullptr anyway.

Upvotes: 3

Related Questions