Ovidiu Firescu
Ovidiu Firescu

Reputation: 405

Warning: variable is uninitialized

I have the following piece of code:

class circularList
{
public:
    circularList() : data(0), next(this) {}
public:
    int data;
    circularList* next;
};

int main()
{
    circularList* root = new circularList;
}

I keep getting a warning saying that variable circularList* next is uninitialized, but I can see if I run the code that is initialized with the address of the pointer root.

Upvotes: 5

Views: 697

Answers (3)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14589

It's either bug or misfeature of static analyzer. It's intended behaviour is to react on code like this:

class circularList
{
public:
    circularList() : data2(0), data1(this->data2) {}
public:
    int data1;
    int data2;
};

data2 actually initialized after data1 (which produces another warning) and expression starting with this, this->XXX, prompts the check. In your case ->XXX is not present and it confuses the analyzer. This should be a regression, because some builds of older compilers (as old as VS2005 or VS2008), or some very ancient gcc or lcc (not stable builds) expressed similar concerns.

There is still a case when this should not be used - if there is a virtual inheritance, or if initialization tries to call a virtual function.

Upvotes: 3

eerorika
eerorika

Reputation: 238311

The pointer is clearly initialised in the example. This appears to be a compiler bug, as there should be no warning. You should report it to the maintainers.

Upvotes: 4

v78
v78

Reputation: 2933

next(this) should bad choice since this is logically not created when passed like this. Maybe use next = this instead in the constructor block.

PS: gcc (GCC) 4.8.5 did not issue any warning.

class circularList
{
public:
    circularList() : data(0) { next = this; }
public:
    int data;
    circularList* next;
};

int main()
{
    circularList* root = new circularList;
    std::cout << root->data << "\n";
    std::cout << root->next->data << "\n";
    root->data = 1;
    std::cout << root->data << "\n";
    std::cout << root->next->data << "\n";
}

Upvotes: -3

Related Questions