posts - 0,comments - 0,trackbacks - 0
1. C++ 的对象指针数组没有多态:
/*
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the

static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual

destructor or the behavior is undefined.

                  --------ISO/IEC 14882:1998 5.35
*/
#include <iostream>
using namespace std;


struct A
{
    virtual ~A()
    {
        cout << "~A\n";
    }
};

struct B : public A
{
  public:
  float m_f;
  virtual ~B()
  {
      cout << "~B\n";
  }
};


int main()
{
    B *p  = new B;
    A *c = p;
    delete c; // All right.

    
// Can not free the Array pointer    
    {
        B *pb = new B[2];
        A *pa = pb; // 数组退化为指针
        void *pv = pb; // 同上
        delete []pa; // delete []pv;
    }
}
2. C++ 构造函数不能调用虚函数一致。

#include <string>
#include <iostream>
#include <vector>
#include <iterator>

using namespace std;
/**
    Base
    / \
Test1 Test2

we want to create Test1/Test2 from any class derived from Base.
 so we just write a copy-CTOR, but nightmares begins.
 see following code: it will cause a terrible bug .
*/
class Base
{
    Base(Base const&);
    const Base & operator=(Base const&);
public:
    Base(){}
    virtual int *Get()const {return 0;}
};

class Test1 :public Base
{
   Test1(Test1 const&);// Notice we hide this for the error.!!!! if you don't,
   
// the compiler will create a useless copy-ctor for you ,
   
// and the following t3 will be copied with anything possible!!
public:
   Test1(){}
   Test1(Base const &rhs)
   {
        cout << "Test1(Base const&)\n";
   }
};

class Test2 :public Base
{
   //Test2(Base const&);
public:
   Test2(){}
   Test2(Test2 const &rhs)
   {
        cout << "Test2(Base const&)\n";
   }
};


int main()
{
    Test1 t1;
    Test2 t2(t1);
    Test2 t3(t2);// error: use of deleted function 'Test2::Test2(const Test2&)'|
}
一般而言拷贝构造函数需要严格按照A(A const &) 来写,PS,赋值函数是可以有多态特征的。所以应该避免编写如同Test2(Base const &)这样的构造函数;如果你注释掉 Test1(Test1 const&)这行,那么在  创建调t3时会调用系统默认的拷贝构造函数. 在大多数情形下,这不是我们需要的。

posted on 2012-06-16 17:35 Dxliu 阅读(65) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理