c ++从函数返回指针时的随机数 [英] c++ random numbers when returning pointer from function
问题描述
我在C ++中有以下代码。每次我运行它,它有不同的输出。为什么会发生这种情况?是不是与内存泄漏有关?
I have the following code in C++ . Everytime I run it ,it has a different output. Why does this happen ? Is it somehow related to memory leak ?
#include <iostream>
using namespace std;
template <class T, class U>
T f(T x, U y)
{
return x+y;
}
int f(int x, int y)
{
return x-y;
}
int main()
{
int *a=new int(4), b(16);
cout<<*f(a,b);
return 0;
}
推荐答案
正常 int
到 f
,因为
int *a=new int(4), b(16);
的工作原理如下:
int *a=new int(4);
int b(16);
因此,在 f
code> T == int * 和 U == int
,然后添加 int
到指针并返回结果指针。因为它不指向你拥有和初始化的内存,解除引用它是UB,并可能产生垃圾或崩溃或做任何喜欢。
Thus, in f
, you have T == int*
and U == int
, then you add the int
to the pointer and return the resulting pointer. As it does not point to memory you own and initialized, dereferencing it is UB and may yield garbage or crash or do whatever it likes.
正如我已经在评论,你不应该尝试通过试错来学习C ++,这真的不会工作,相信我。而是从一本好书中系统地学习它。您将看到,首先不需要使用指针。
As I already said in the comments, you should not try to learn C++ by trial and error, that really will not work, believe me. Learn it systematically from a good book instead. You will see that there is no need to use pointers for this in the first place.
这篇关于c ++从函数返回指针时的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!