1

i don't understand fully this problem. This is my function and i need return class with unique_ptr how can i this?

my list:

std::list<std::unique_ptr<Maths> > l_MathsList;

my function

Maths* Maths2::FindMathsID(int iID)
{
    auto mpClass= std::unique_ptr<Maths>();
    for (auto&& it : l_MathsList)
    {
        if (iter->IsMy(iID)) { 
            mpClass = std::move(it); 
            }
            break; 
        }
    }
    return mpClass; // compiler error
9
  • 5
    You've declared a function which returns a Maths* and then you've elected to return a std::unique_ptr. The compile error likely tells you as much. Either change the return type or quit making a smart pointer. Commented Jul 2, 2021 at 21:58
  • @SilvioMayolo thanks for your comment! Can u give example for return type? Compiler error: cannot convert 'std::unique_ptr<MathFuncs::Maths>' to 'MathFuncs::MathFuncs*' in return Commented Jul 2, 2021 at 21:59
  • 1
    If you intend to return a unique_ptr, then the return type should be std::unique_ptr<Maths>. But note that, once you've called this function once, some prefix of the list l_MathsList (which I presume is an instance variable) will be left empty and therefore inaccessible. Commented Jul 2, 2021 at 22:01
  • @SilvioMayolo i need this but i wish using smart ptr working func: ` Maths * mClass= NULL; for (auto it = l_MathsList.cbegin(); it != l_MathsList.cend(); it++) { if ((*it)->IsMy(iID)) { mClass= *iter; if ( (parameter2)!= NULL) { mClass->ReCalc(parameter2); } break; } } return mClass; ` Commented Jul 2, 2021 at 22:03
  • 1
    If the requirement is to "return a ...", then declare your function to so just that. Work on figuring out how to accomplice the task and ... question the task. Commented Jul 2, 2021 at 22:07

1 Answer 1

1

You probably just want to return a non-owning pointer to the collection element right?

In that case just use .get():

Maths* Maths2::FindMathsID(int iID)
{
    for (auto& it : l_MathsList)
    {
        if (it->IsMy(iID))
          return it.get();
    }
    return nullptr;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.