c++从函数返回指针时的随机数

c++ random numbers when returning pointer from function

本文关键字:随机数 指针 返回 函数 c++      更新时间:2023-10-16

我用c++编写了以下代码。每次我运行它,它都有不同的输出。为什么会发生这种情况?这是否与内存泄漏有关?

#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;
}

你正在传递一个指针和一个正常的intf,因为

int *a=new int(4), b(16);

就像

int *a=new int(4);
int b(16);

因此,在f中,您有T == int*U == int,然后将int添加到指针并返回结果指针。因为它不指向你拥有的和初始化的内存,解引用它是UB,可能产生垃圾或崩溃或做任何它喜欢的事情。

正如我在评论中已经说过的,你不应该试图通过试错来学习c++,相信我,那是行不通的。而是从一本好书中系统地学习。您将看到,根本不需要使用指针。