当 new/malloc 函数退出时,从 new/malloc 返回的指针如何保存在范围内?

How is the returned pointer from new/malloc kept in scope when the new/malloc function is exited?

是否创建了某种共享指针?

这是一道 XY 题。我的最终目的是在我的 class 中声明一个 private 变量,它是一个指针,但是在 public 函数和 return 中分配并填充一个数组 return 指向 private变量。我怎样才能合法地将函数中分配的变量保留在范围内,而不仅仅是将其保留在某种准状态。下面的代码是否实际上将函数中分配的内存传递给接收 returned 值的指针,或者内存只是挂起? main() 中对 delete 的最终调用是否实际上取消了 returned_data 指向的内存的分配,就好像内存本身是使用以下语句分配的:returned_data = new char [15]?

最后,我真的需要将其扩展为char **这样的二维指针。我知道编译器需要以某种方式被告知至少数组的一个维度,所以这可能是不可能的。

class MyClass
{
    private:
        char *returned_data;
    public:
        char *fetch_data();
};

MyClass::fetch_data()
{
    char *data_pointer;

    data_pointer = new char [15];

    strcpy(data_pointer, "Hello_World!");

    return data_pointer;
};

main()
{
    MyClass ClassName;

    ClassName.returned_data = ClassName.fetch_data();

    // Do whatever

    delete [] ClassName.returned_data;
};

我刚刚恢复了我的编程速度,因为我的编程已经停用了很多年,所以代码中可能存在缺陷。这给出了总体思路。这不是我正在使用的实际代码,因为该代码与我的应用程序中的其他代码混合在一起。欢迎任何corrections/suggestions。

Is some kind of shared pointer created?

不,只是一个指针。它是 return 通过复制函数从函数中提取出来的,给另一个具有相同值的指针,即指向相同的东西。

How can I legitimately keep the variable allocated in the function in scope and not just leave it in some quasi-state

不是"allocated in the function";它是从免费存储中分配的,并一直保留到使用 delete 显式解除分配为止。只是 return 指针。分配的数组不关心哪些指针指向它,并且如果它们被复制或销毁也不会改变状态。

Does the code below actually pass the memory allocated in the function off to the pointer receiving the returned value or is the memory just left hanging?

它 return 是指向该内存的指针,您可以使用它来访问和释放内存。它不是 "left hanging" 只要你有指向它的指针。

Does the final call to delete in main() actually de-allocate the memory pointed to by returned_data as if the memory itself had been allocated using this statement: returned_data = new char [15]?

是的。 returned 指针与 new 的结果具有相同的值(因此指向相同的内存),因此它(或具有该值的任何其他指针)可用于删除它。

但是你不想在没有充分理由的情况下玩弄指针——你很可能会犯错误,导致内存泄漏甚至更糟。使用智能指针,或者像std::vectorstd::string这样的容器,更方便的管理动态内存。