c++从函数返回指针时的随机数
c++ random numbers when returning pointer from function
我用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;
}
你正在传递一个指针和一个正常的int
到f
,因为
int *a=new int(4), b(16);
就像
int *a=new int(4);
int b(16);
因此,在f
中,您有T == int*
和U == int
,然后将int
添加到指针并返回结果指针。因为它不指向你拥有的和初始化的内存,解引用它是UB,可能产生垃圾或崩溃或做任何它喜欢的事情。
正如我在评论中已经说过的,你不应该试图通过试错来学习c++,相信我,那是行不通的。而是从一本好书中系统地学习。您将看到,根本不需要使用指针。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么递增指针会给出一个随机数,而不是内存地址
- 使用指针用随机数填充数组
- 从函数返回指针给我随机数
- 如何使用指针用随机数填充二维数组
- c++从函数返回指针时的随机数
- 是堆栈指针,是伪随机数的良好来源