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 に答える