当有人说你不应该在构造函数中使用'this'关键字时,我读了一些文章,而其他人则说完全相反......
现在我的主要问题是:在构造函数中使用“this”安全吗?
这个问题导致其他人:
- 对象创建是如何进行的?
- 什么时候创建一个类的成员?在调用构造函数之前?
以下是在 windows 7 上使用 VS2012 的一些示例:
class FirstClass
{
int m_A;
public:
FirstClass( int a ) : m_A( a )
{
std::cout << this->m_A << std::endl;
// ^^^^
}
};
和 :
class ThirdClass; // forward decl
class SecondClass
{
public:
SecondClass( ThirdClass* iTC )
{
// ...
}
};
class ThirdClass
{
SecondClass* m_SC;
public:
ThirdClass():
m_SC( new SecondClass( this ) )
// ^^^^
{
//...
}
};
这些例子有效,但是否有可能出现未定义的行为?