Re: [cpp] my problem(关于函数的默认参数和变量的生存周期)

巤邓 tdzl2003 at gmail.com
Sun Mar 23 20:19:13 CST 2008


第一个问题
你不妨再做一个重载
int foo(int a,int b);
inline int foo(int a){return foo(a,a);}

第二个问题
你理解错"临时变量"的概念了
书上的临时变量指栈上分配的东西
比方说
int a;
return &a;
是不安全的
但是堆上分配的,只要你没释放,就可以返回。
int *a = new int;
return a; //OK

int **foo(){
int *a = new int;
return &a; //also not ok.
}


2008/3/2 陈超 <alpha.1986 at gmail.com>:

> 第一个问题,应该是参数入栈顺序的问题吧。。。,用__stdcall或者__cdecl等,具体参考msdn
>
>
> 第二个问题,应该是你理解错了吧,c++ primer上指的返回临时对象的指针应该是指
>
> int* retpoint()
> {
>      int tmp;
>      int* p=&tmp;
>      return p;
> }
>
> 这样的错误代码。
>
> 对于new的问题,我想你应该再把书好好看看,这是c++很基本基本的问题。
>
>
> 在08-3-2,marryme <beyond0924 at gmail.com> 写道:
>
> > #include <iostream>
> > #include <string>
> > #include <iterator>
> > #include <list>
> > #include <algorithm>
> > using namespace std;
> > template<typename T, typename ForwardIterator=T::iterator>//模板的默认参数
> > struct  print
> > {
> >
> > void operator() (T& coll, ForwardIterator it=coll.begin() )//函数的默认参数
> > {
> >
> >    copy( coll.begin(),coll.end
> > (),ostream_iterator<T::value_type>(cout,"\n"));
> >
> > }
> > };
> > //现在我已经有了一个list<int> a;
> > print(a);//编译不能通过,提示begin()找不道所属的class sturct
> > print(a,a.begin());//编译通过
> > 主要的是我希望函数总的第二个参数有第一个参数决定,下面是个简单的例子:
> > int test(int a, int b=a)
> > {
> >   return b;
> > }
> > 函数的第二个变量b由第一个变量a决定,但是在vs2005环境下不能编译通过,想问问你有没有什么办法解决又或者有现成的语法实现之。
> >
> >
> > 下面是第二个问题:就比较简单了
> > c++ primer 中明确指出,不要返回指向临时
> > 对象的指针。但是看下面一段代码:
> > int* point(int a=0)
> > {
> > int* p=new int(a);//这是一个临时变量
> > cout<<"in fuction"<<endl<<p<<"   "<<*p<<endl;
> > return p;
> > }
> > int main()
> > {
> > int* p=point();
> > cout<<p<<"  "<<*p<<endl;
> >    return 0;
> > }
> > 执行之后主函数难正确的输出结果0,这就说明
> > 在函数中如果一个临时变量本身是通过指针产生的
> > 就可以继续存在。
> > 然后下面的代码:
> > 当返回指向临时变量的指针,但变量不是通过指针生成的,就会出现不可预计的错误。如以下代码:
> > #include <iostream>
> > using std::cout;
> > using std::endl;
> > int* point(int a=0)
> > {
> > cout<<"in fuction"<<endl<<&a<<"   "<<a<<endl;
> > return &a;
> > }
> > int main()
> > {
> > int* p=point();
> > cout<<p<<"  "<<*p<<endl;
> >    return 0;
> > }返回的结果不可预计
> > 所以我想知道在函数中通过new操作符产生的变量生存周期难道是整个程序?
> >
> > _______________________________________________
> > Cpp mailing list
> > Cpp at codingnow.com
> > http://codingnow.com/mailman/listinfo/cpp
> >
>
>
>
> --
> Chao Chen
>
> P.L.A. Information Engineering University
>
> Zhengzhou,Henan,China
> Blog:http://blog.alpha1986.cn
> Email:alpha.1986 at gmail.com
> _______________________________________________
> Cpp mailing list
> Cpp at codingnow.com
> http://codingnow.com/mailman/listinfo/cpp
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://codingnow.com/pipermail/cpp/attachments/20080323/3626d13c/attachment.html


More information about the Cpp mailing list