【发布时间】:2015-11-10 16:39:32
【问题描述】:
考虑以下程序:
#include <iostream>
struct T
{
public:
T() : b(6)
{
T t=*this; // copy constructor
std::cout<<t;
}
int b;
friend std::ostream& operator<<(std::ostream&,const T& t);
}t;
std::ostream& operator<<(std::ostream& o,const T& t)
{
o<<t.b<<'\n';
return o;
}
int main() { }
上面的程序对我来说确实很奇怪。在构造函数中创建类的对象可以吗?这段代码的行为是否明确定义?
【问题讨论】:
-
虽然技术上有效,但这是个坏主意。请阅读:Should you use the this pointer in the constructor?
-
在构造函数完成之前,不会认为对象已被构造。我不太相信
*this的这种用法是正确的 -
@M.M: 为什么ideone.com/BsIm3G 这个程序会导致运行时错误。当我在 g++ 4.8.1 上的本地计算机上编译并运行它时,我在运行时收到错误消息 test.exe 已停止工作。为什么?是什么原因?
-
@PravasiMeet 该程序导致递归,因为
T t;出现在T的默认构造函数中 -
@M.M:哦,我没有注意到递归。谢谢。
标签: c++ object constructor