读书人

来自Effective c++ 上的一个小程序编

发布时间: 2012-06-15 19:37:05 作者: rapoo

来自Effective c++ 上的一个小程序,编译无错但是运行就有问题
来自13节,关于初始化顺序

C/C++ code
class Wacko {public:Wacko(const char *s): s1(s), s2(0) {}Wacko(const Wacko& rhs): s2(rhs.s1), s1(0) {}private:string s1, s2;};Wacko w1 = "Hello world!";Wacko w2 = w1;

这个程序理论上的结果是不是
w1:s1="hello world", s2=0
w2:s1=0,s2="hello world"

我运行这个程序就出错,不知道为啥,
出错信息:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
请高人指点下这个程序以及内部潜在的问题,谢谢。!

[解决办法]
s2(0)这个0表示什么意思?
[解决办法]
0 会被当做一个指针, 用空指针来初始化 string 会出错. 把它去掉就好了:
Wacko(const char *s): s1(s), s2() {}
Wacko(const Wacko& rhs): s2(rhs.s1), s1() {}
[解决办法]
类Class A{
int a;
int b;
};

构造函数A():b(0),a (0);
{
}

调用构造函数时不是先b = 0;而是先a = 0,再b = 0。
[解决办法]
这个初始化列表的问题要分情况讨论的
如果是继承类,要先出始化基类成员,在按初始化列表的顺序初始化数据,
如果不是集成类,那么按照变量定义的顺序初始化变量,出始化列表顺序无意义

读书人网 >C++

热点推荐