delegating-constructor

Calling constructor with braces instead parantheses

给你一囗甜甜゛ 提交于 2019-12-11 10:49:54
问题 I recently realized that in C++11 we can call a delegating initializer-list constructor like Foo() : Foo{42} // delegate to Foo(initializer_list<>) Is this syntax correct? It seems to be, although I would have expected to always use parentheses when calling a function, like Foo({42}) . The example code below compiles fine in both clang++ and g++ #include <iostream> #include <initializer_list> struct Foo { Foo() : Foo{42} // I would have expected invalid syntax, use Foo({42}) { std::cout <<

MSVC direct constructor call extension

喜你入骨 提交于 2019-12-04 22:09:25
问题 In this response, tloveless pointed out that it's possible in MSVC to use this->foo::foo(42); for constructor delegation to directly call a constructor: #include <iostream> struct foo { int m; foo(int p) : m(p) { std::cout << "foo("<<p<<")\n"; } foo() : m(0) { this->foo::foo(42); std::cout << "foo(), " << m << "\n"; } }; int main() { foo f; std::cin.ignore(); } I was surprised that this even compiles in MSVC; clang++, g++ and me agree it's illegal, e.g. [class.ctor]/2 "Because constructors do

MSVC direct constructor call extension

被刻印的时光 ゝ 提交于 2019-12-03 14:07:58
In this response , tloveless pointed out that it's possible in MSVC to use this->foo::foo(42); for constructor delegation to directly call a constructor: #include <iostream> struct foo { int m; foo(int p) : m(p) { std::cout << "foo("<<p<<")\n"; } foo() : m(0) { this->foo::foo(42); std::cout << "foo(), " << m << "\n"; } }; int main() { foo f; std::cin.ignore(); } I was surprised that this even compiles in MSVC; clang++, g++ and me agree it's illegal, e.g. [class.ctor]/2 "Because constructors do not have names, they are never found during name lookup" However, MSVC doesn't even emit a warning

How to forward overloaded constructor call to another constructor in C++/CLI

独自空忆成欢 提交于 2019-11-28 07:39:17
问题 I know that there is no way to do this in pure C++, but I was wondering if it is possible to call a constructor from another constructor's initialization list in C++/CLI, same way one can do it in C#. Example: ref class Foo { Foo() {} Foo(int i) : Foo() {} } 回答1: It is called a "delegating constructor". It is not available in the language yet. But there's a formal proposal, you'll find it in annex F.3.1 of the language specification. Given Microsoft's stance towards C++/CLI, that is unlikely