为什么不使用以下内容:
struct Foo
{
int x;
};
int main()
{
Foo &foo = *new Foo();
foo.x = 7;
std::cout << foo.x << std::endl;
delete &foo;
}
毕竟,必须尽可能使用引用,并且使用这种方法,一旦我们最初取消引用,我们就永远不必担心再次忘记它。缺点是什么?
编辑:
我知道 operator ->
,忘记了我的意思
int &n = *new int;
n = 7;
int *m = new int;
*m = 7; //here you can forget it
最佳答案
你会发生内存泄漏。你必须在函数结束时做这样的事情:
delete &foo;
这是个坏主意。
关于c++ - 构造动态对象时取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16492607/