c++ - 从类指针到 int 的无效转换

标签 c++ memory-management new-operator

<分区>

我无法弄清楚下面代码中的问题所在

class Node
{
    private:
        int index, value;

    public:
        Node(int index=0, int value=0):index(index),value(value){}

        int getIndex()
        {
            return index;
        }

        int getValue()
        {
            return value;
        }
};


int main()
{
    Node n = new Node(10,10);
    return 0;
}

我明白了

invalid conversion from Node* to int

最佳答案

new 返回一个指针。您不能将指针分配给 n , 这是一个 Node .快速解决方法是将有问题的行更改为 Node * n = new Node(10,10);auto n = new Node(10,10); .

但是使用new不再是现代 c++ 中动态创建对象的推荐解决方案。喜欢auto n = std::make_unique<Node>(10, 10);相反,这使得 n一个smart pointer .通过使用智能指针,您不必手动跟踪所有权,也不必记住 delete。你的对象恰好一次。您还可以使您的代码在出现意外异常时更加健壮。你需要 #include <memory> .参见 std::make_unique std::make_shared :

#include <memory>

int main()
{
    auto n = std::make_unique<Node>(10,10);
    return 0;
}

虽然在这种情况下,似乎不需要动态分配。只需使用 Node n{10, 10};就足够了。

关于c++ - 从类指针到 int 的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52520420/

相关文章:

java - 查找JVM分配的内存

C++ new 分配比预期更多的空间

c++ - 如何安全地从内存中清除使用 new 关键字创建的对象(具有属性)?

C++ 内存泄漏 new 运算符

c++ - STD 文件流损坏? (内部文件缓冲区为空,无法读取输入)

c++ - 增量备份 : how to track file deletions

c++ - include 语句外包含守卫

c++ - 为什么这个包含 rand() 的 C++11 代码多线程比单线程慢?

iphone - 使用仪器进行内存分析

c++ - 从自身获取进程的私有(private)内存页(如VMMap)