How do I get / implement the "Uninitialized warning usage" message for a built-in variable of a class member type?
#include<iostream>
struct a{
int x;
};
int foo() {
a oa;
return oa.x;
}
int bar() {
int a;
return a;
}
int main() {
auto val = foo();
std::cout<<val<<"\n";
return 0;
}
If we compile and run the above sample.cpp
, we get the following output:
$g++ -Wall -std=c++11 sample.cpp -o sample
sample.cpp: In function βint bar()β:
sample.cpp:13:9: warning: βaβ is used uninitialized in this
function [-Wuninitialized]
return a;
^
$ ./sample
-1643562384
$ ./sample
991591024
For the above program, the compiler issues a warning about uninitialized use of a variable a
inside bar()
. However, no compiler warnings are raised when a function foo()
tries to use a variable of an x
object of oa
type struct a
.
I am aware of the function c++11 universal initialization
, and if we define struct a
as shown below then the default built-in constructor int
will be called by the default constructor struct a
.
struct a {
int x{};
}
I wanted to know that with the new features like is it type traits/static_assert
possible to implement such a warning in the above situation ?.
Things like this are possible in languages ββlike C # since everything comes from a generic class and therefore the default constructor takes care of it. Bjarne Stroustrup mentioned in his " C ++ programming language ". The reason for this complication is to improve performance in rare critical cases .
struct Buf {
int count;
char buf[16β1024];
};
We can use it Buf
as a local variable without initialization before using it as a target for an input operation. But I think if we can implement some kind of mechanism for this, in many situations it would be great. This would be really useful, since uninitialized variables are used as the main source of uninterrupted errors.
source to share
This can only really work in very simple cases, as shown here. There are other cases where the compiler cannot even tell if a member variable has been initialized before use. For example:
// a.h
void init_a(a & an_a);
// a.cpp
#include "a.h"
void init_a(a & an_a) {
an_a.x = 1;
}
// b.cpp
#include "a.h"
int test() {
a oa;
init_a(oa);
return oa.x;
}
Since it is init_a()
not defined in the same translation unit as and test()
, the compiler cannot know if a member is assigned x
by the time the statement was reached return
.
Thus, such a warning can only be raised when the compiler can prove that the member cannot be initialized, and there are many situations where the compiler could not tell and could not generate a warning. Therefore, with such a warning, one could only catch extremely simple cases and would be of very limited usefulness.
source to share