I am reading about implementing Rule of Three/Five, and found examples on cppreference as well as this canonical answer on SO. I know that it doesn't make sense to use a char*
in modern C++, but the point is to create some code which will need those three/five methods.
Cppreference starts with something like:
class rule_of_three
{
char* cstring;
rule_of_three(const char* s, std::size_t n) // n is passed from the public ctor
: cstring(new char[n]) // allocate
{
std::memcpy(cstring, s, n); // populate
}
public:
rule_of_three(const char* s = "")
: rule_of_three(s, std::strlen(s) + 1)
{ }
...
But the class doesn't check if s
is null
at all -- isn't this a potential problem?
I tried writing it like this:
class rule_of_three
{
char* cstring;
rule_of_three(const char* s, std::size_t n)
{
if (!s) throw std::runtime_error("s cannot be null");
cstring = new char[n]; // allocate
std::memcpy(cstring, s, n); // populate
}
but now gcc complains that
rule_of_three::cstring
should be initialized in the member initialization list [-Weffc++]
So, what would be the correct approach here?