-1

Clang doesn't check if all class members have been initialized inside overloaded assignment operators/copy constructors in the contrary to Lint. Instead of that Clang check usage of uninitialized variables. Such approach should be sufficient but what in case of the static casting as it is in following code:

#include <iostream>
using namespace std; 

struct B 
{
    int member;
    B()
    {
    member =111;
    }
    B(B const & )
    {   
    }
    B& operator=(B const & )
    {
    }

};
struct D : public B 
{
    void hello() const 
    {   
    cout << "member value " << member << "\n";
    }
    D()    
    {
    }
};

int main()
{

    D d;
    D d2  = d;
    B* br ;

    D* another_d = static_cast<D*>(br); 
    another_d->hello();

}

Static casting is just coping byte by byte and it can't guarantee that all members are initialized however it is a gap for an unsecure code and it can be avoided by checking body of copy consructor as it is done in lint case.

So it could be an input for a Feature Request. What is your opinion?

Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
  • 2
    You have undefined behavior. In most cases the compiler is not mandated to tell you about this or have it fail to compile. C++ gives you plenty of ways to shoot yourself in the foot. In turn it lets you do some really cool stuff. – NathanOliver Apr 10 '18 at 13:07
  • 2
    Your program does initialize (and doesn't modify) `member` in *all* the declared objects. There's nothing to report on that front. – StoryTeller - Unslander Monica Apr 10 '18 at 13:08
  • 2
    The rest of the post may stand, but I think the final line is wrong in implying that SO is a valid place to solicit opinions about whether you should post a feature request on someone else's project. – underscore_d Apr 10 '18 at 13:10

1 Answers1

1

Here you violate aliasing rules*:

B* br;
D* another_d = static_cast<D*>(br); 

Since br doesn't actually point to a D*, you should not cast to one. As a result, this is undefined beavior.

And then here is more undefined behavior:

another_d->hello();

Trying to dereference the pointer another_d at all (even as a B*) is undefined because B* br remains uninitialized.

Anything goes when we're in UB land.


*[expr.static.cast]:

...If the prvalue of type “pointer to cv1 B” points to a ``B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the behavior is undefined.

AndyG
  • 39,700
  • 8
  • 109
  • 143