0

可能的重复:
什么是三法则?

以下代码最多输出垃圾或崩溃:

#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
};

我真的很想知道为什么-甚至不应该触摸该对象,因为我按值传递它...

4

1 回答 1

3

在 C++ 眼中,关于你的代码的一切都是不好的,抱歉。尝试这个

#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;
}

在本例中,您不必担心内存分配和销毁、printf 格式字符串或 strcpy。它更加健壮。

带有类的 C(这是您正在编写的)绝对是错误的,并且盲目地忽略了为使语言更安全、更容易而无需开销而创建的功能。

于 2012-03-09T15:18:01.877 回答