由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 引用的几个基本问题,有点糊涂
相关主题
C++ questiona C++ question
c++标准函数传递一问[合集] 为什么 const member 不能是 static.
请问c++为什么会编译失败?What're the three types of memory allocated for C++ variables?
请教一个基础C++问题question about c++ constructor
我写的这个C++错在哪里?问一个简单C++问题
请问这个C++程序有什么问题吗question about const reference
问一个C++ set和unordered_set iterator的问题C++ 的 问题
请教:函数后面的 throw() 有意义么?c++ 不自动initialize变量么?
相关话题的讨论汇总
话题: int话题: pn话题: fp话题: const话题: fpc
进入Programming版参与讨论
1 (共1页)
s****y
发帖数: 8
1
void f(const int &a) {;}
void fpc(const int* &pa) {;}
void fp(int* &pa) {;}
int main()
{
int* pn, na[2], n = 1;
pn = &n;
f(n); // ok
fpc(pn); // error: invalid initialization of reference of type 'const int*&'
from expression of type 'int*'
fp(pn); // ok
fp(na); // error: invalid initialization of non-const reference of type 'int
*&' from a temporary of type 'int*'
}
请问上面这两个错的原因是什么?
f(n)和fpc(pn)之间有什么区别,除了改成传递指针变量之外
fp(pn)和fp(na)又有什么区别?
多谢指点
s****y
发帖数: 8
2
可能这个问题太弱了,不过也请帮忙解释一下,多谢了

&'

【在 s****y 的大作中提到】
: void f(const int &a) {;}
: void fpc(const int* &pa) {;}
: void fp(int* &pa) {;}
: int main()
: {
: int* pn, na[2], n = 1;
: pn = &n;
: f(n); // ok
: fpc(pn); // error: invalid initialization of reference of type 'const int*&'
: from expression of type 'int*'

m******n
发帖数: 21
3
这个问题一点也不弱:)
第一个问题可以归结为下面的问题:
const int * p;
int* & q = p;
或者
int *p;
const int * &q = p;
都是不允许的。q被认为是p的alias, 他们对指向内存的write access必须相同。
可能type theory里面有更深的原因。但是我能够想到的理由是,如果他们对
memory的访问权限不一样, 通过p或者q中的一个会改变同一个内存的值。
这样很容易产生bug。 所以编译器这样选择是合适的。
至于第二个问题:
当你call fp(na)的时候, 从错误信息看,compiler应该是从 int [] 创建了一个
temporary 的int *的变量。 但是由于你在fp被定义为传入一个int *&pa 而不是
int *const &pa的值,你可能改变这个临时变量的值, compiler认为这是不允许的。
compiler可以让你编译通过,但是这样会产生不可预料的后果。
解决第一个问题的办法是定义 pn 为const int *类型。
解决第二个问题的方法是定义fp为 void fp(int *con

【在 s****y 的大作中提到】
: void f(const int &a) {;}
: void fpc(const int* &pa) {;}
: void fp(int* &pa) {;}
: int main()
: {
: int* pn, na[2], n = 1;
: pn = &n;
: f(n); // ok
: fpc(pn); // error: invalid initialization of reference of type 'const int*&'
: from expression of type 'int*'

1 (共1页)
进入Programming版参与讨论
相关主题
c++ 不自动initialize变量么?我写的这个C++错在哪里?
static initialization dependency c++请问这个C++程序有什么问题吗
How to initialize object in constructor?问一个C++ set和unordered_set iterator的问题
几个问题请教:函数后面的 throw() 有意义么?
C++ questiona C++ question
c++标准函数传递一问[合集] 为什么 const member 不能是 static.
请问c++为什么会编译失败?What're the three types of memory allocated for C++ variables?
请教一个基础C++问题question about c++ constructor
相关话题的讨论汇总
话题: int话题: pn话题: fp话题: const话题: fpc