Today, I saw a question like this on stackoverflow.
The second output statement of the program below has a problem.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class C {
public:
char* s;
C(char* s_) {
s=(char *)calloc(strlen(s_)+1,1);
strcpy(s,s_);
};
~C() {
free(s);
};
};
void func(C c) {};
void main() {
C o="hello";
printf("hello: %s\n",o.s); // works ok
func(o);
printf("hello: %s\n",o.s); // outputs garbage
};
After reading it, I probably analyzed the cause.
In C ++, If we assign a value to the object of a class, or when the form parameter is passed to another function, if the class contains a variable of the pointer type, by default, C ++ copies the pointer instead of the content pointed to by the pointer.
In the above example,
func(o);
This function passes the real parameter O to the form parameter, but since the member s of O is a pointer, the pointer of the real participation parameter points to the same memory space, however, after the function is complete, the parameters are parsed,
Free (s); at the same time, the directed memory space is cleared, so when the main program returns again, the original pointer to the memory space has no data, so the output is incorrect.
)
The following is a solution written by a foreign company.
#include <iostream>
class C {
std::string s;
C(const std::string& s_)
: s(s_){}
};
std::ostream& operator<<(std::ostream& os, const C& c){
return os << c.s;
}
void func(C& c){
// do what you need here
}
int main(){
C c("hello");
std::cout << c << '\n';
func(c);
std::cout << c << std::endl;
return 0;
}
He wrote this method from another perspective and did not solve the pointer problem. In fact, I feel better to write a copy constructor, assign values to pointers. This prevents errors.