Scoping and passing classes by value?

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: %sn",o.s);  // works ok
    func(o);
    printf("hello: %sn",o.s);  // outputs garbage
};

I really wonder why - the object should not even be touched because Im passing it by value ...


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.

链接地址: http://www.djcxy.com/p/73190.html

上一篇: 是i = post的行为

下一篇: 根据价值确定范围并传递课程?