Checking if pointer args are null / Field should be initialized in the member initialization list for a raw pointer

Lou

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?

eerorika

But the class doesn't check if s is null at all -- isn't this a potential problem?

That is a problem only if null is passed to the constructor. Otherwise it is not.

the second snippet actually has a null check which prevents me from using the member init list.

Having a null check doesn't prevent you from using the member init list. Here is an example:

static char*
init(const char* s, std::size_t n))
{
    if (s)
        return new char[n];
    else
        throw std::runtime_error("s cannot be null");
}

rule_of_three(const char* s, std::size_t n)
    : cstring(init(s, n))
{

So, what would be the correct approach here?

Ignoring the detail that using a bare owning pointer probably isn't a correct approach in the first place: Both checking for null and not checking for null are correct approaches. One is safer and the other is more efficient. You must choose which one is more important for your use case. Regardless, initialising members is recommended.


P.S. As dratenik points out in a comment, the public constructor relies on the pointer not being null before delegating to the private constructor, so the check in the private constructor is too late.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Should the member of class be a pointer?

Checking for Null Pointer in Ada

Pointer of structure initialization to NULL

C++ pointer member initialization

Are pointer to a member of this allowed in object initialization?

pointer to struct member without initialization

Member initialization list for smart pointer to user-defined struct

Should we NULL every raw pointer after it is used?

Initialization of data member in initialization section using this pointer

Pointer automatically gets initialized to NULL

why is a pointer member initialized to a non-zero?

Dynamically allocated member pointer is not zero initialized?

Can enums be initialized in an member initialization list?

C++ proper pointer member initialization

Assigning pointer member of a struct to null

Alternatives for storing a class member as a raw pointer

Can I use scalar initialization in a struct whose member is a pointer to pointer?

Java null pointer exception after checking if null

Kotlin null pointer when checking for null state

Getting null pointer even though button is initialized

Should I use a raw pointer here?

Aggregate initialization, set member pointer to same struct member

Should member method be const if returning a pointer or reference

Should a std::string class member be a pointer?

Initialize std::unique_ptr as a raw array pointer is initialized

C pointer address changes on null pointer initialization in function

Function pointer in a std::thread Args... list

Pointer to pointer member Struct

Is there a ?. operator for Java to perform null pointer checking?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive