Shadow
Shadow

Reputation: 447

Safety with referencing uninitalized variables in C++

(Assuming includes/namespace std/prototypes in the lines above code)

1) Is it safe to create a reference to a declared variable that isn't initialized?

myVariable is declared in line 2 and then myRef is set to reference the uninitialized myVariable in line 3.

Is this something that shouldn't be done?

1- int main(){
2-     string myVariable;
3-     string& myRef = myVariable;
4- {

2) Is it safe to initialize an uninitialized variable by passing itself through as a reference to a function?

myVar is declared on line 2 and then initialized on line 3 but it uses its uninitialized self as an arguement in the function askText. Inside the function on line 3('7'), the reference text_to_initialize gives myVar a value finally.

Is it safe to intialize with yourself as an arguement in line 3?

1- int main(){
2-     string myVar;
3-     myVar = inputText(myVar);
4- }
5- 
6- string inputText(string& text_to_initialize){
7-     cin >> text_to_initialize;
8-     return (text_to_initialize + "!");
8- }

Upvotes: 0

Views: 64

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283981

All of the above are ok, since none of them perform lvalue-to-rvalue conversion on the indeterminate value. It's even permitted to bind a reference to a variable with non-trivial initialization before that initialization has completed.

The rule is found in section 8.5:

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17). [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. —end note ] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:

and the cases involve narrow character types, so not applicable here. What is important is that no evaluation produces an indeterminate value (which would happen as a result of lvalue-to-rvalue conversion).

As John points out, in your particular case, the default initialization of a std::string is not "no initialization", so you don't even have an indeterminate value to begin with. But you'd be ok even for primitive types with no default initialization.

Upvotes: 3

Related Questions