A question about passing class objects on stackoverflow

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.