考虑以下计划:
#include <string>
#include <iostream>
class B {
private:
std::string s;
public:
B() { s = fun(); }
std::string fun() { return "hello"; }
void print() {
std::cout << s;
}
};
int main(){
B b;
b.print();
}
Run Code Online (Sandbox Code Playgroud)
输出是 Hello
我的问题是:
我怀疑的是我如何在b对象上调用一个尚未由构造函数创建的函数.
问题是为什么程序打印id:0,id:1,id:2,42而不是id:42,id:43,id:44,45.
int main()
{
int id = 0;
auto f = [id] () mutable {
std::cout << "id: " << id << std::endl;
++id; // OK
};
id = 42;
f();
f();
f();
std::cout << id << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在读取异常时,我知道在抛出对象时,总是基于静态类型信息构造对象。如果发生异常,我们如何抛出子类对象?以下是《更有效的C ++》一书中的几行内容:
Run Code Online (Sandbox Code Playgroud)class Widget{...}; class SpecialWidget: public Widget {...}; void passAndThrowWidget() { SpecialWidget localSpecialWidget; ... Widget& rw = localSpecialWidget; throw rw; // this throws an exception of type widget! }即使rw指向,也会在此处引发Widget异常
SpecialWidget。那是因为rw的静态类型是Widget,而不是Special-Widget。rw实际上是指SpecialWidget,您的编译器并不关心。他们只关心rw的静态类型。
这就解释了为什么会发生这种情况,但没有提供解决问题的方法。