2

我正在写一堂课,这个疑问出现了。这是undef. 行为?另一方面,我不确定它是否被推荐,或者它是否是一个好的做法。如果我确保在 init 函数中不抛出异常,它是一个吗?

//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;
}

提前致谢

4

3 回答 3

6

完全没问题。一旦你进入构造函数的主体,所有的成员都已经被初始化并且可以使用了。(然后,主体将完成创建完全构造的对象所需的更多工作。)

但它的风格很差。更好的是:

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

并消除所有的混乱。


异常与安全无关,构造函数可以随意抛出。事实上,如果你不能成功地构造一个对象,那么抛出一个异常是首选的做法。

于 2010-04-15T04:19:11.460 回答
0

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

于 2010-04-15T04:28:02.490 回答
0

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 :)

于 2010-04-15T05:46:16.620 回答