错误、漏洞、问题 - 页 3101

 

在b3095中,我运行一个脚本。

template <typename T>
void f1(T* const Ptr) {Print(__FUNCSIG__);}

template <typename T>
void f1(T* & Ptr) {Print(__FUNCSIG__);}


class X {};

void OnStart()
  {
//---
   const X* Ptr = new X;
   
   f1(Ptr);                               //void f1<const X>(const X*&)
   f1<const X>(Ptr);                      //void f1<const X>(const X*&)
   
   //дальше непонятно!
   f1<const X>((const X*) Ptr);           //void func_902::f1<const X>(const X*const)
   f1<const X>((const X* const) Ptr);     //void func_902::f1<const X>(const X*const)
   f1<const X>((X*)Ptr);                  //void func_902::f1<const X>(const X*const)
 
   delete Ptr;
  }

如果你去掉重载f1(T* & Ptr),所有5个调用都返回 void f1<const X>(const X*const)。

这是某种特征吗?

 

请解释。

第*1*行给出了一个编译器错误--预期。

但第*2行的编译和工作正常。为什么?

int f(int & p) {return p;}

class X
  {
public:
   const int         i;
                     X(){}
        /*1*/      //X(X& x) : i(f(x.i)) {f(x.i);}  //'i' - constant variable cannot be passed as reference
        /*2*/        X(X& x) : i(f(x.i)) {}          //OK
  };

void OnStart()  {}
 
mktr8591 #:

请解释。

第*1*行给出了一个编译器错误--预期。

但第*2行的编译和工作正常。为什么?

你需要证明一个明显的矛盾(你改变了const值)。

int f( int &p ) { return p = !p; }
struct X {
        const int i;
        X( int i ) : i( i )      {}
        X( X& x  ) : i( f(x.i) ) {}
};
void OnStart()
{
        X x1( 1 );
        const int i =  x1.i;
                                { X x2 = x1; }
        Print(    i == x1.i );  //Результат: false - не может быть
}
而你建议有经验的用户和开发者都应该猜测
 
A100 #:

价值变化

关于交易、自动交易系统和交易策略测试的论坛

mql5语言的特殊性、微妙性和技巧性

我的 想法是使用mql5作为外汇交易系统,我想在自己的实践中使用它。

是否可以改变一个类 的常量对象 字段或调用其非常量方法?-你可以!
template <typename T>
T GetMe( const T Ptr )
{
  return((T)Ptr);
}

class A
{
public:  
  int i;
};

void OnStart()
{
  const A a;

  GetMe(&a).i = 1;
  
  Print(a.i); // 1
}

我自己不喜欢这种芯片。我以为我已经投保了未经授权的访问。遗憾的是!当然,它对常量结构不起作用。所以要记住这个漏洞。


 
A100 #:

你需要证明一个明显的矛盾(你已经改变了const的值)。

而你建议有经验的用户猜测 和开发人员
我没有想到会描述得这么详细...
 
fxsaber #:
但在你的例子中,你有一个明确的(通过一个函数)const T到T的转换--也就是一个 "合法化 "的漏洞。
 
mktr8591 #:
但在你的例子中,你有一个明确的(通过一个函数)const T到T的转换--也就是一个 "合法化 "的漏洞。
((A*)(&a)).i = 1;    
 
fxsaber #:
类似地--(const A*)转换为A*。
 
mktr8591 #:
类似地--(const A*)转换为A*。
((A)a).i = 1;
 
fxsaber #:

你的例子明确地将常量转换为非常量, 就干净了