简体   繁体   English

为什么C ++方法不应该返回解引用的指针?

[英]Why shouldn't a C++ method return a dereferenced pointer?

I'm very new to C++ (and studying Java). 我是C ++(和学习Java)的新手。 This is from HW but I think I've answered the HW issue and I'm just trying to get a better sense of pointers. 这是来自硬件的,但是我想我已经回答了硬件问题,我只是想更好地了解指针。

Say I have the following method: 说我有以下方法:

int cubed(int a) {
  int * ptr;
  *ptr = a * a * a;
  return *ptr;
}

This compiles and works fine with the following: 可以使用以下代码进行编译和正常工作:

int test = cubed(3);

I'm trying to get a sense of why it's bad to return a dereferenced pointer. 我试图弄清为什么返回取消引用的指针不好。

This question says that memory leak is a problem but I'm not sure why. 这个问题说内存泄漏是一个问题,但是我不确定为什么。 Maybe because I don't understand what happens to a dereferenced pointer. 也许是因为我不了解取消引用的指针会发生什么。

Does the lvalue just hang around indefinitely at that point? 那时候左值是否无限期地徘徊? Do you have to actually delete the pointer? 您是否必须删除指针? Any insight would be appreciated. 任何见识将不胜感激。

The question you read is different. 您阅读的问题有所不同。 Say you had this code: 假设您有以下代码:

int cubed(int a) {
  int* ptr = new int;
  *ptr = a * a * a;
  return *ptr;
}

Now, you'd be leaking the dynamically-allocated int , because you'd return a copy of it and never delete the original. 现在,您将泄漏动态分配的int ,因为您将返回它的副本并且永远不会delete原始副本。

Your code is actually worse because, instead of allocating with new , you're simply writing through an uninitialised pointer to memory that is not yours. 您的代码实际上更糟,因为,您不是通过new进行分配,而是通过未初始化的指向您自己的内存的指针进行写入。 In effect, you're writing to an int that does not exist. 实际上,您正在写入一个不存在的int

What you should be doing is this: 应该做的是这样的:

constexpr int cubed(const int a)
{
   return a*a*a;
}

Or just invoke std::pow(value, 3) at the call site. 或者只是在调用站点上调用std::pow(value, 3)

There is no memory link in your code, but there is another big bug. 您的代码中没有内存链接,但是还有另一个大错误。

You declare int * ptr; 您声明int * ptr; inside the function int cubed(int a) , so it is a local variable. 在函数int cubed(int a) ,因此它是一个局部变量。

The value of ptr will be random - might be NULL, might point to garbage, might point to some perfectly valid address. ptr的值将是随机的-可能为NULL,可能指向垃圾,可能指向某个完全有效的地址。 You don't initialize the variable ptr , so your code will sometimes crash. 您无需初始化变量ptr ,因此您的代码有时会崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM