c++ - 关于引用和指针的问题

标签 c++ pointers reference

考虑这个简单的类:

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/

相关文章:

c++ - C++数据结构的时间范围查询

c++ - 指向 >> 运算符的 fstream 问题的指针?

c - 不兼容的返回类型

python - 当 python 列表迭代是和不是引用时

c++ - 从 DLL 中获取 HModule

c++ - libuvc 程序无法编译

c++ - 如何从另一个类中的私有(private)指针指向的类中获取私有(private)信息?

具有适用于左值和右值的引用参数的 C++ 函数

recursion - 使用可变引用对app_state进行递归更新更新

c++ - 施奈尔河豚