C ++'new'关键字和内存管理不一定带'new' [英] C++ 'new' keyword and memory management not necessarily with 'new'

查看:103
本文介绍了C ++'new'关键字和内存管理不一定带'new'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





只是一个快速的记忆管理问题,让我说我有以下内容:



Hi,

Just a quick memory management question, let's say I have the following:

const std::vector<int> intArray = {1, 2, 3};
delete intArray;

这应该为数组分配内存然后再将其释放。



这在这种情况下如何工作?

This should allocate memory for the array then free it up again.

How does this work in this situation?

doSomething({1, 2, 3});

void doSomething(const std::vector<int> arr)
{
        // whatever
}

这里,没有机会删除原始数组。我应该做以下哪一项?



1.没有,那个记忆将被管理。



2.

Here, there's no opportunity to delete the original array. Which of the following should I do?

1. Nothing, that memory will be managed already.

2.

const std::vector<int> arr = {1, 2, 3};
doSomething(arr);
delete arr;

void doSomething(const std::vector<int> arr)
{
        // whatever
}



3.


3.

const std::vector<int>* arr = {1, 2, 3};
doSomething(arr);

void doSomething(const std::vector<int>& arr)
{
        delete arr;
}





我不确定1和2的语法是否正确,请通知我任何问题你看到那里了。



我尝试过:



- -------------------------------------------------- --------------------------



I'm not sure if the syntax for 1 and 2 are correct either, please notify me of any issues you see there.

What I have tried:

------------------------------------------------------------------------------

推荐答案

您是否尝试过编译此代码:



Have you tried to compile this code:

const std::vector<int> intArray = {1, 2, 3};
delete intArray;





我认为不行,因为你应该在删除intArray上收到错误,例如表达必须是一个指针。



你只能用new删除在堆上创建的对象,而不是像intArray这样的堆栈对象:看看操作员删除


如果您在堆栈中声明一个对象,就像在您的超出范围时,它会自动销毁。



正如您在其他问题中已经提到的那样,您应该通过引用将其传递以避免创建副本。 />


所以它应该是:

If you declare an object on the stack as in your case, it is destroyed automatically when going out of scope.

As already noted at your other question, you should pass it by reference to avoid creating a copy.

So it should be:
{
    const std::vector<int> arr = {1, 2, 3};
    doSomething(arr);

    // arr goes out of scope here at the end of the block
    // The desctructor is called and any memory is freed
}

void doSomething(const std::vector<int>& arr)
{
    // do something
}



如果按值传递数组:


If you pass the array by value:

// A temporary copy of the passed array is created and assigned to arr
void doSomething(const std::vector<int> arr)
{
    // do something

    // The destructor of arr is called here when returning from the function
    // The original array passed from the caller still exists
}


这篇关于C ++'new'关键字和内存管理不一定带'new'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆