The result was correct.
Can this warning be ignored and what errors might be raised and what would be better?
Here is my very simple code:
#include<iostream>
using namespace std;
class Person{
public:
Person(int a,int b):age(a),height(&b){//Warning specific location here:height(&b)
cout<<"initialize"<<endl;
cout<<"height"<<*height<<endl;
}
Person(const Person &p){
age = p.age;
height = new int(*p.height);
}
int age;
int *height;
};
void test02(){
Person p1(10,150);
}
int main(int argc, char const *argv[])
{
test02();
return 0;
}
Please forgive my poor level of code. If you have any ideas about the programming style or this issue, please feel free to share them.
Any help will be appreciated.
The idea behind this code is I’m trying to figure out how do I initialize a pointer variable.
The results of the code meet my expectations.
>Solution :
You are initializing the pointer to point to variable b but that is a parameter taken by value. The b object is destroyed after the function(constructor) exits, leaving the pointer dangling.
You want
Person(int a,int b):age(a),height(new int(b)){
cout<<"initialize"<<endl;
cout<<"height"<<*height<<endl;
}
If you come from Java/C# background, C++ has very different value semantics – new should be only used if you need to manage lifetime manually and even then smart pointers are preferred. T object; is not some hidden pointer to heap, = means deep copy for T. If you need references, use T& or T* – unless you ask for reference semantics, you do not get it.