Search code examples
c++private-constructor

How to create an array with Object that has private copy constructor


I have a struct that have some member and a Object that have private copy constructor, How can I create an array that include this object. For example: I have an Object:

class Image
{
   ...
   private:
      Image(const Image&);
      Image& operator=(const Image&);
      u8* pixel;
      int width;
      int height
}

struct ImageInformation
{
   Image image;
   int resolution;
}

I want to create an array for ImageInformation : vector but this is forbidding


Solution

  • You'll have to define the move ctor and move assignment operator on the Image class since the default implementations would be deleted because you provided a user declared copy ctor and copy assignment operator.

    You should then be able to use the vector with no issue.

    class Image
    {
    public:
        Image( int height, int width ) 
            : height_{ height }
            , width_{ width }
        { }
    
        Image( Image&& ) = default;
        Image& operator=( Image&& ) = default;
    
        Image( const Image& ) = delete;
        Image& operator=( const Image& ) = delete;
    
    private:
        int height_;
        int width_;
    };
    
    class ImageInformation
    {
    public:
        explicit ImageInformation( Image image )
            : image_{ std::move( image ) }
        { }
    
    private:
        Image image_;
    };
    
    
    int main( )
    {
        std::vector<ImageInformation> containers;
    
        Image image{ 10, 10 };
        containers.emplace_back( std::move( image ) );
    }