mercredi 13 juin 2018

C++11 / Non Constructible but Copyable?

I observed that if I explicitly delete only constructor and destructor of a class then the resultant implementation deletes copy constructor & move constructor, but the compiler still makes copy assignment and move assignment operators implicitly available! Which in turn makes assignment possible!

My question is what is the rational of this? What is the use case where this can be used. Following is an example code for reference:

# ifndef MOEGLICH_H_
# define MOEGLICH_H_

# include <cstdint>

class Moeglich final
{
public :

   explicit
   Moeglich()                                 = delete   ;
  ~Moeglich()                                 = delete   ;

/*
// With explicit deletion
   Moeglich& operator=(const Moeglich& other) = delete   ; 
   Moeglich(const Moeglich& other)            = delete   ;
   Moeglich&& operator=(Moeglich&& other)     = delete   ; 
   Moeglich(Moeglich&& other)                 = delete   ;
*/

   static constexpr uint16_t Egal(const uint8_t& var_) noexcept
   {
      return static_cast< uint16_t > ( var_ ) ;
   }

};

# endif

# include <cstdlib>
# include <iostream>
# include <type_traits>

int main(int argc, char* argv[])
{

   std::cout << std::boolalpha 
             << "Is constructible      : " << std::is_constructible<Moeglich>::value        << std::endl 
             << "Is destructible       : " << std::is_destructible<Moeglich>::value         << std::endl 
             << "Is copy constructible : " << std::is_copy_constructible<Moeglich>::value   << std::endl 
             << "Is move constructible : " << std::is_move_constructible<Moeglich>::value   << std::endl 
             << "Is copy assignable    : " << std::is_copy_assignable<Moeglich>::value      << std::endl 
             << "Is move assignable    : " << std::is_move_assignable<Moeglich>::value      << std::endl 
             << "Is assignable         : " << std::is_assignable<Moeglich, Moeglich>::value << std::endl 
              ;

/* Following were what I wanted to prevent anyway :

   const Moeglich mom {} ;
   Moeglich pop {} ;
   Moeglich foo {} ;
   foo = mom ;
   foo = std::move(pop) ;

*/

   return EXIT_SUCCESS ;

}

Regards,

Sumit

Aucun commentaire:

Enregistrer un commentaire