Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ null value and this pointer

Tags:

c++

this

I'm a newbie in C++, trying to study C++. I have a block of code in Java like this:

public List<String> getDiagnosticTroubleCode() {
    if (diagnosticTroubleCode == null) {
        diagnosticTroubleCode = new ArrayList<String>();
    }
    return this.diagnosticTroubleCode;
}

How can I compare the disgnosticTroubleCode with null value? and set it as a new List. I already override the std::list to make it use like List in Java. And then I want to return the diagnosticTroubleCode field within the object this. I hope that you guys can help me with this. Trying to study about this pointer and null.

Here is my header in C++ :

class RUNTIME_EXPORTS DiagnosticTroubleCode {
            protected:
                List diagnosticTroubleCode;
            public:
                List getDiagnosticTroubleCode();
            };
like image 837
Nguyễn Đức Tâm Avatar asked Feb 14 '26 16:02

Nguyễn Đức Tâm


1 Answers

Your code appears to desire only instantiating diagnosticTroubleCode on first use. Frankly, I find that somewhat odd, since an instance of an otherwise-empty std::list<std::string> would be rather benign. Regardless, this is one way to do that.


class DiagnosticTroubleCode 
{
protected:
    std::unique_ptr<std::list<std::string>> diagnosticTroubleCode;

public:
    std::list<std::string>& getDiagnosticTroubleCode()
    {
        if (!diagnosticTroubleCode)
            diagnosticTroubleCode = std::make_unique<std::list<std::string>>();
        return *diagnosticTroubleCode;
    }
};

Note that the member getDiagnosticTroubleCode will return a reference to the new (or existing) instantiated list. If you decide to forego latent instantiation (I recommend doing so), the code becomes considerably simpler:

class DiagnosticTroubleCode 
{
protected:
    std::list<std::string> diagnosticTroubleCode;

public:
    std::list<std::string>& getDiagnosticTroubleCode()
    {
        return diagnosticTroubleCode;
    }
};

If the latter is possible (and frankly, I cannot see how it isn't), pursue that first. IN both cases above the member is returned by reference, not value or address. This would most-closely resemble what you're probably familiar with.

Best of luck.

like image 80
WhozCraig Avatar answered Feb 16 '26 07:02

WhozCraig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!