-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpassDynamicMemoryRetbyRef.cpp
More file actions
63 lines (47 loc) · 1.44 KB
/
passDynamicMemoryRetbyRef.cpp
File metadata and controls
63 lines (47 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
The snippet shows how to pass the dynamically allocated memory
as a return value by reference from a function.
Never Pass a function's local variable as return value by reference.
*/
#include <iostream>
using namespace std;
//Correct Methods
int *squarePtr(int);
int &squareRef(int);
//Wrong Methods - They will issue warning but not errors
//Please avoid this type of logical errors
int *squarePtrW(int);
int &squareRefW(int);
int main() {
int number = 8;
cout << number << endl; // 8
cout << *squarePtr(number) << endl; // 64
cout << squareRef(number) << endl; // 64
cout << "\n\nWrong Methods : \n";
cout << *squarePtrW(number) << endl; // 64
cout << squareRefW(number) << endl; // 64
system("pause");
return 0;
}
//Returned as a pointer - Correct Method
int * squarePtr(int number) {
int * dynamicAllocatedResult = new int(number * number);
return dynamicAllocatedResult;
}
//Returned as a reference - Correct Method
int & squareRef(int number) {
int * dynamicAllocatedResult = new int(number * number);
return *dynamicAllocatedResult;
}
//Returned as a pointer - Wrong Method
int * squarePtrW(int number) {
int localResult = number * number;
return &localResult;
// warning: address of local variable 'localResult' returned
}
//Returned as a reference - Wrong Method
int & squareRefW(int number) {
int localResult = number * number;
return localResult;
// warning: reference of local variable 'localResult' returned
}