考虑这个简单的类:
class Test {
public:
Test() { data = 0; };
Test(int integer);
int getData() { return data; }
~Test();
private:
int data;
};
如果我写:
Test t = *new Test;
是否会在堆上创建一个新的Test
对象,然后将其复制到临时Test
对象t
?会不会有内存泄漏?
还有为什么这个无效?
Test* t = new Test(0);
int i = *t.getData();
但这不是:
Test* t1 = new Test(0);
Test& t2 = *t1;
int i = t2.getData();
我知道我可以简单地执行 t->getData()
但我不明白为什么上面的例子不起作用?
最佳答案
Would a new Test object be created on the heap and then copied to the temporary Test object t? And there would be a memory leak?
是的,是的。
Also why can't I do this:
member of object access operator (.
) 优先于 *
。您可以执行 (*t).getData()
。
关于c++ - 关于引用和指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54148160/