Search code examples
c++copy-constructorrule-of-three

"attempting to reference a deleted function" for copy constructor


I am trying to get my head around the Rule of 5.

I have a class Renderable, which defines a custom destructor, so it seemed like a good candidate for the Rule of 5. This class creates some resources in its constructor, so my first thought was that I should prevent copying:

class Renderable {

public:

    Renderable(const Sprite&) {
        // Allocate resources
    }

    ~Renderable() {
        // Free resources
    }

    // Prevent copying
    Renderable(const Renderable& other) = delete;

}

I have another class, Unit, which creates a Renderable in the initializer list of its constructor:

class Unit {

public:

    Unit(const Sprite& sprite) :
            renderable(Renderable(sprite)) {}

private:

    Renderable renderable;

}

I would expect this to call the regular Renderable constructor, but instead I get the error:

Renderable::Renderable(const Renderable &)': attempting to reference a deleted function

Why is this trying to call the copy constructor?

I even tried added debug lines to the copy constructor, but nothing is printed:

Renderable(const Renderable& other) : sprite(other.sprite) {
    std::cout << "copy constructor";
}

Solution

  • In addition to what others have said, I think you meant to write:

    Unit::Unit(const Sprite& sprite) :
        renderable(sprite) {}
    

    This invokes the converting constructor Renderable(const Sprite&) to initialise renderable directly, no copying involved.

    Live demo