5
#include <atomic>
std::atomic<int> outside(1);
class A{
  std::atomic<int> inside(1);  // <--- why not allowed ?
};

error:

prog.cpp:4:25: error: expected identifier before numeric constant
prog.cpp:4:25: error: expected ',' or '...' before numeric constant

In VS11

C2059: syntax error : 'constant'
4
  • Try inside = std::atomic<int>(0); Commented Sep 9, 2012 at 12:31
  • I think there is a historic problem with () inside the class. Have you tried = instead of braces ? Commented Sep 9, 2012 at 12:32
  • @iammilind guess what. It works outside but not inside..... Commented Sep 9, 2012 at 12:34
  • related and other one. Commented Sep 9, 2012 at 12:39

1 Answer 1

8

In-class initializers do not support the (e) syntax of initialization because the committee members that designed it worried about potential ambiguities (For example, the well-known T t(X()); declaration would be ambiguous and does not specify an initialization but declares a function with an unnamed parameter).

You can say

class A{
    std::atomic<int> inside{1};
};

Alternatively a default value can be passed in the constructor

class A {
  A():inside(1) {}
  std::atomic<int> inside;
};
Sign up to request clarification or add additional context in comments.

10 Comments

although correct ATM both gcc and VC11 doesn't support {1} :(. +1
Non-static data member initializers (N2756) are supported by Clang 3.0 and upwards.
@MatthieuM. I'm on windows :(. My favorite IDE is VS and i like clang but it doesnt support windows
@acidzombie24: I can understand the appeal of VS (especially its debugger). As for Windows support in clang, it's moving along but yes, unfortunately, it's still lagging behind. Personally (having a Windows computer at home too), I use codeblocks for edition on a shared folder... and I have a Ubuntu VM for compiling/running my programs :)
This is C++11 syntax, and it hasn't made it into many compilers yet.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.