Scoping and passing classes by value? [duplicate]
Question
Possible Duplicate:
What is The Rule of Three?
The following code outputs garbage at best or crashes:
#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
};
I really wonder why - the object should not even be touched because Im passing it by value ...
Solution
everthing about your code is bad in the eyes of C++, sorry. try this
#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;
}
In this example you don't have to worry about memory allocation and destruction, printf format strings or strcpy. It is much more robust.
C with classes (which is what you are writing) is categorically wrong, and blindly ignores the features that were created to make the language safer and easier without overhead.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow