0

ALL,

What are the conditions where the compiler itself declares the function deleted?

Consider following:

class Foo
{
public:
    Foo();
    virtual void func1() = 0;
    virtual void func2() = 0;
    virtual bool func3();
}

class Bar : public Foo
{
public:
    Bar(int param1);
    virtual void func1() override;
    virtual void func2() override;
    virtual bool func3() override;
}

class Baz
{
public:
    Baz(std::unique_ptr<Foo> &foo)
    {
        m_foo = foo;
    }
private:
    std::unique_ptr<Foo> m_foo;
}

I am getting a compiler error on the assignment (MSVC 2019):

attempting to reference a deleted function

This is compiled with C++11.

TIA!

Igor
  • 5,620
  • 11
  • 51
  • 103

1 Answers1

1

The error seems to come from the line m_foo = foo

unique_ptr cannot be copied thus unique_ptr& operator=(const unique_ptr&) is deleted.

Unique pointers are about exclusive ownership. Thus, if you want to transfer ownership to baz, you will need to move the unique_ptr.

For example:

Baz(std::unique_ptr<Foo> foo) : m_foo{std::move(foo)}
{
}

For the conditions a compiler declares a special member deleted (by declared, we mean regular declaration or =default or =deleted):

  • if a destructor or copy op or assignment op is declared then move operators are marked as deleted,
  • if only one of the move operator is declared, the other one is marked as deleted,
  • if a move copy op or a move assignment op is declared, the regular copy/assignment op are marked as deleted.
nop666
  • 585
  • 2
  • 6
  • `std::move()` is C++14. I work with C++11. Also, I think I found the cause - `operator=(const std::unique_ptr &)` is marked as deleted in the documentation, I don't know how to fix it. (ref. http://www.cplusplus.com/reference/memory/unique_ptr/operator=/) – Igor Aug 15 '20 at 07:33
  • `std::move` comes with c++11 and its move semantics. For the operator, as I said in the answer, it is intended. Maybe a shared ownership using `shared_ptr` is more suitable in your case? – nop666 Aug 17 '20 at 07:03