按值确定类的作用域并传递类

Scoping and passing classes by value?

本文关键字:作用域      更新时间:2023-10-16

可能重复:
什么是"三条规则"?

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

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

我真的很想知道为什么——这个物体甚至不应该被触摸,因为我是按价值传递的。。。

在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(这就是你正在写的)是完全错误的,并且盲目地忽略了为使语言在没有开销的情况下更安全、更容易而创建的功能。