When returning an object, I can't just use {} after the class name
Taking this educational code about nested classes as an example:
class enclose {
struct nested { // private member
void g() {}
};
public:
static nested f() { return nested{}; }
};
int main() {
//enclose::nested n1 = e.f(); // error: 'nested' is private
enclose::f().g(); // OK: does not name 'nested'
auto n2 = enclose::f(); // OK: does not name 'nested'
n2.g(); }
When copying and pasting this code in Microsoft Visual Studio 2012, I get an error at the line
static nested f() { return nested{}; }
in which the problem is with how the function is returned nested. This isn't the first time I've seen codes that return a value this way, but I usually ignore it and take longer. Is this a compiler problem?
+3
source to share
1 answer
Line
return nested{};
uses new C ++ 11 braced-initialization and value-initializes object. As you see here, Visual Studio 2012 (VC11) doesn't support braced-initialization, so you get a compile-time error.
The only solution is to use
return nested();
instead, or update your compiler.
+5
source to share