在这个真正允许的函数中,或者我们有未定义的行为
in this really allowed function or we have undefined behavior
对于交换函数,我们有两种选择:参考样式:
void swap (int &a, int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
和指针样式:
void swap (int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
ref风格绝对合法,但指针风格有一些问题,当我们尝试使用此函数变量通过值传递,而不是通过引用传递,即使它们是指针-事实上,我们试图在函数之外使用局部变量的内存,并且可能在某一天,在某些机器中我们有未定义的行为,代码也适用于示例:在此代码中:
main()
{
//
{
int i=12;
int *j=&i;
}
//in this area, there is not variables i and j, but phisically threre is
// unsafe-relationship between this address: &i and what point to (12) ,
//any more logic according to this assumtion may be work
//but not safe -in the scene of undefined behavior-
我不知道你从哪里得到的关于函数外部的句子。你不应该相信他们,因为那句话是错的。
它应该是"在函数返回调用未定义行为后访问局部变量或参数"。(这是我自己的话。)
要获得正式的措辞,请查看C++标准。要查找的关键字是生存期、存储持续时间和未定义行为。
相关文章:
- 为什么当我们有常量引用时创建临时对象?
- 既然我们有内联变量,extern const 还有用吗?
- 我们应该如何使用枚举类进行索引(或者我们应该更好地避免这种情况)?
- 我们可以在INI文件中使用 #ifdef 宏,或者我们如何限制INI文件中写入的设置的编译?
- 如果我们有一个基*类,如何访问派生模板类的成员函数
- 当我们有纯虚函数时,如何煽动一个对象?
- 如果我们有 (N)RVO,当实际调用移动构造函数时?
- 如何通过键和值以及在C 中的结果映射中比较两个地图?我们有任何STL API吗?
- 为什么我们需要模板 <int N>,因为我们有类初始化
- 我们是否需要担心 32 位或 64 位整数,或者我们只使用 'int'
- 如果我们有对的矢量,如何进行下限二进制搜索
- 如果我们有glBindBuffer,"glGenBuffers"真的很重要吗?
- 需要找到总的平方差,并且代码没有产生正确的答案,我们有一部分代码,必须填写空白
- 给定许多垂直或水平段及其终点的坐标(x1,x2,y1,y2),我们有多少个相交
- 为什么我们有一个类型不匹配
- 在这个真正允许的函数中,或者我们有未定义的行为
- 当我们有数字和字符串时,>>运算符如何工作
- 当我们有用于设置值的 setter 时,为什么我们使用参数化构造函数
- 即使我们有.h文件,C 何时包含CPP
- 在类映射中,当我们有迭代器时,constiterator的必要性是什么