开发者

Call a non member function on an instance before is constructed

I'm writing a class, and this doubt came up. Is this undef. behaviour? On开发者_如何学JAVA the other hand, I'm not sure its recommended, or if its a good practice. Is it one if I ensure no exceptions to be thrown in the init function?

//c.h
class C{

    float vx,vy;
    friend void init(C& c);
public:
    C();

};


//c.cpp
C::C()
{
   init(*this);
}

void init(C& c) //throws() to ensure no exceptions ?
{
  c.vx = 0;
  c.vy = 0;
}

Thanks in advance


It's completely fine. Once you enter the body of the constructor, all the members have been initialized and they are ready to use. (The body is then to finish up any more work that needs to be done to create a fully constructed object.)

But it is poor style. Better is just:

C::C() :
vx(), vy() // or vx(0), vy(0) if you prefer to be explicit
{}

And do away with all the mess.


Exceptions have nothing to do with safety, constructors are free to throw. In fact, if you can't successfully construct an object then throwing an exception is the preferred course of action.


By the time the control reaches the constructor all the variables would have got default values.


I can think of one specific case where this might bite you. If C is intended to be a base class, allowing a reference to it to escape to non-member functions may cause surprise. In the base class case constructors are more special because the derived class hasn't been constructed yet and virtual functions call the base class rather than the derived class. Non member functions may not be expecting to get an object in this state, and because they don't look like constructors it would be easy to introduce bugs by forgetting that.

It still isn't undefined behaviour though - just surprising defined behaviour :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜