Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-static data member initializers questions

Tags:

c++

c++11

I've built MinGW from trunk-version GCC-4.7.0: http://code.google.com/p/mingw-builds/downloads/list

In the description of changes of this version it is said that non-static data member initializers are implemented: http://gcc.gnu.org/gcc-4.7/changes.html

http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2756.htm

When I try to compile such an example:

#include <iostream>
#include <string>

struct type {
   type()
      :i(33)
   {}

   int i;
   std::string s("string");
};

int main() {
   type t;
   std::cout << t.i << " : " << t.s << std::endl;
}

I get a ton of errors, and this one is in the end:

main.cpp:16:35: note: 'std::string (type::)(int) {aka std::basic_string (type::)(int)}' is not derived from 'const std::basic_string<_CharT, _Traits, _Alloc>' main.cpp:16:35: note: could not resolve address from overloaded function 't.type::s'

But according to the documentation, the code is correct.

like image 708
niXman Avatar asked Oct 06 '11 12:10

niXman


People also ask

What is non-static data member?

Non-static data members are the variables that are declared in a member specification of a class.

Where can a non-static reference member variable of a class be initialized?

Member initialization Non-static data members may be initialized in one of two ways: 1) In the member initializer list of the constructor.

Can you initialize static data member non-static block?

Yes... a non-static method can access any static variable without creating an instance of the class because the static variable belongs to the class.

What is Nsdmi?

NSDMI - Non-static data member initialization.


1 Answers

The problem seems to be an ambiguity in determining whether you are declaring a function or an object, and the compiler is choosing the function.

You should try initializing the string using this syntax instead:

std::string s = "string";

If we follow the link from the GCC Release Notes concerning non-static data member initializers (proposal N2756), they mention this in problem 1, with this resolution note:

CWG had a 6-to-3 straw poll in Kona in favor of class-scope lookup; and that is what this paper proposes, with initializers for non-static data members limited to the “= initializer-clause” and “{ initializer-list }” forms.

like image 133
JRL Avatar answered Nov 07 '22 01:11

JRL