ctor-initializer

What is this weird colon-member (“ : ”) syntax in the constructor?

半世苍凉 提交于 2019-11-25 23:56:02
问题 Recently I\'ve seen an example like the following: #include <iostream> class Foo { public: int bar; Foo(int num): bar(num) {}; }; int main(void) { std::cout << Foo(42).bar << std::endl; return 0; } What does this strange : bar(num) mean? It somehow seems to initialize the member variable but I\'ve never seen this syntax before. It looks like a function/constructor call but for an int ? Makes no sense for me. Perhaps someone could enlighten me. And, by the way, are there any other esoteric

Does a const reference class member prolong the life of a temporary?

风格不统一 提交于 2019-11-25 21:47:45
问题 Why does this: #include <string> #include <iostream> using namespace std; class Sandbox { public: Sandbox(const string& n) : member(n) {} const string& member; }; int main() { Sandbox sandbox(string(\"four\")); cout << \"The answer is: \" << sandbox.member << endl; return 0; } Give output of: The answer is: Instead of: The answer is: four 回答1: Only local const references prolong the lifespan. The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of