将非常量传递给常量 - *(new foo())和foo()作为参数传递时的差异

时间:2015-04-06 17:45:27

标签: c++

我想知道这两者之间的区别。我期待他们两个都与语句A

具有相同的行为
void myfunctReference(foo& f) 
{
        std::cout << "Function called";
}

以下是来电者

声明A:

 myfunctReference(foo()); //Fail - OK Agreed. Because a temp is being sent as a parameter to a function who parameter is not constant. temporaries can only bind to constant references
声明B:

myfunctReference(*(new foo())); //Allowed - Why ? isnt *(new foo()) a temp ?

1 个答案:

答案 0 :(得分:4)

  

为什么? isnt *(new foo())一个临时工具?

不,这不是“临时”。它是一个左值表达式,指的是newed对象,一个在有人对其调用delete之前一直存在的对象。将非常量左值引用绑定到这样的表达式是完全正确的。

内存泄漏是什么。

相关问题