C ++函数返回引用和内存 [英] C++ functions returning a reference and memory

查看:73
本文介绍了C ++函数返回引用和内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有几个创建对象的函数.例如,如果您有一个使像这样的对象的函数:

I have in my project a couple of functions that create objects. For example, if you have a function that makes an object like this:

int& f()
{
    int *i = new int(5);
    return *i;
}

然后打电话给您

int x = f();

或类似的

std::cout << f();

在函数中创建的int会发生什么?是像普通变量一样处理引用,还是我做错了什么?如果是这样,那么制作对象的正确方法是什么?

what happens to the int that was created in the function? Is the reference handled like a normal variable or am I doing something terribly wrong? And if so, what is the correct way to make objects?

推荐答案

确实,这是完全错误的.您忘记参考的那一刻就是您泄漏资源的那一刻.而您正在使用int x = f();进行此操作.

This is terribly wrong, indeed. The moment you forget about your reference is the moment you'll leak a resource. And you're doing just that with int x = f();.

与第二种情况std::cout << f();相同-如果您不打算动态分配intdelete,请不要使用它.

Same with the second case, std::cout << f(); - don't use this at all if you aren't going to delete that dynamically allocated int.

int也会按值传递给std::basic_ostream::operator<<,并进行复制.这实际上并不重要,没有正常的代码会接受引用,然后调用delete &ref;.

int is also passed to std::basic_ostream::operator<< by value, a copy is made. This doesn't actually matter, no normal code would accept a reference and then call delete &ref;.

以下是您的链接: RAII

我无法从人为的示例中知道您想要什么,但可以考虑按值返回,或者在多态的情况下使用智能指针.

I can't know what you want from your contrived example, but consider returning by value, or using smart pointers in case of polymorphism.

这篇关于C ++函数返回引用和内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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