删除对dereferenced int的引用

时间:2017-02-01 05:09:51

标签: c++ reference return-by-reference

即使以下代码编译并运行正常,我想知道它是否是有效的c ++代码?

int main()
{
        int *i= new int;
        cout<<*i;

        int &ref=*i;
        cout<<ref;

        delete &ref; //Especially is this statement valid?
        return 0;
}

如果有效则必须有效:

int& getInt() {
    int* i = new int;
    return *i;  // OK?
}
int main(){
    int& myInt = getInt(); // these two lines are same as shown in the example above ?
    delete &myInt;   //is this OK too?
}

1 个答案:

答案 0 :(得分:3)

它是正确的代码,它适用于所有平台和编译器。

但是,它可能不是最佳做法,因为当被叫方保留对象的所有权时,通常会使用引用。

相关问题