Igor
Igor

Reputation: 6285

Conditions to declare function deleted by c++

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!

Upvotes: 0

Views: 56

Answers (1)

nop666
nop666

Reputation: 603

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.

Upvotes: 1

Related Questions