代码之家  ›  专栏  ›  技术社区  ›  tyrondis

在构造函数中要做什么(不做)

  •  39
  • tyrondis  · 技术社区  · 14 年前

    我想问你关于C++中构造函数的最佳实践。我不太确定我应该在构造函数中做什么,不应该做什么。

    我应该只在属性初始化、调用父构造函数等时使用它吗? 或者我可能会在其中加入更复杂的函数,比如读取和解析配置数据,设置外部库A.S.O。

    还是应该为此编写特殊函数?RESP init() / cleanup() ?

    专业人士和骗子在这里是什么?

    我发现,例如,当使用 () 清除() . 我可以将堆栈上的对象创建为类属性,并在构建之后对其进行初始化。

    如果我在构造函数中处理它,我需要在运行时实例化它。然后我需要一个指针。

    我真的不知道怎么做决定。

    也许你能帮我?

    13 回复  |  直到 6 年前
        1
  •  23
  •   Matthieu M.    14 年前

    class Vector
    {
    public:
      Vector(): mSize(10), mData(new int[mSize]) {}
    private:
      size_t mSize;
      int mData[];
    };
    

    class Vector
    {
    public:
      Vector(): mSize(0), mData(0) {}
    
      // first call to access element should grab memory
    
    private:
      size_t mSize;
      int mData[];
    };
    

    // in the constructor
    Setting::Setting()
    {
      // connect
      // retrieve settings
      // close connection (wait, you used RAII right ?)
      // initialize object
    }
    
    // Builder method
    Setting Setting::Build()
    {
      // connect
      // retrieve settings
    
      Setting setting;
      // initialize object
      return setting;
    }
    

        2
  •  28
  •   Stephane Rolland    6 年前

    class A
    {
    public:
        A(){ doA();} 
        virtual void doA(){};
    }
    
    class B : public A
    {
    public:
        virtual void doA(){ doB();};
        void doB(){};   
    }
    
    
    void testB()
    {
        B b; // this WON'T call doB();
    }
    

    void doA();


    class A
    {
    public: 
        void callAPolymorphicBehaviour()
        {
            doOverridenBehaviour(); 
        }
    
        virtual void doOverridenBehaviour()
        {
            doA();
        }
    
        void doA(){}
    };
    
    class B : public A
    {
    public:
        B()
        {
            callAPolymorphicBehaviour();
        }
    
        virtual void doOverridenBehaviour()
        {
            doB()
        }
    
        void doB(){}
    };
    
    void testB()
    {
       B b; // this WILL call doB();
    }
    

    virtual doOverridenBehaviour()

        3
  •  15
  •   Steve M    14 年前
        4
  •  10
  •   towi    14 年前

    RAII exception safety

    void func() {
        MyFile f("myfile.dat");
        doSomething(f);
    }
    

    MyFile doSomething(f) f

    • virtual

        5
  •  6
  •   Daniel Daranas    13 年前

    init()

    class std::string begin() end() c_str()

        6
  •  4
  •   blahster    14 年前

        7
  •  4
  •   Arun    14 年前

    What all to do in the constructor?
    

        8
  •  4
  •   CashCow    14 年前

        9
  •  3
  •   Nemanja Trifunovic    14 年前

        10
  •  2
  •   Julio Santos    14 年前

        11
  •  2
  •   Nim    14 年前

        12
  •  1
  •   Dainius    14 年前

        13
  •  1
  •   yegor256    6 年前