C ++ 0x Member Initialization without Constructor

In N3257, I found an example using initialization elements without a constructor , which is good. I think this is possible because it is a POD.

template<typename T> struct adaptor { NonStdContainer<T>* ptr; // <- data member T* begin() { return ptr->getFirst(); } T* end() { return ptr->getLast() + 1; } }; void f(NonStdContainer<int>& c) { for (auto i : adaptor<int>{&c}) // <- init { /* ... */ } } 

When I played with this example, I replaced * with & , because I don't like the original pointers:

 template<typename T> struct adaptor { NonStdContainer<T>& ptr; // <- data member, now REF T* begin() { return ptr->getFirst(); } T* end() { return ptr->getLast() + 1; } }; void f(NonStdContainer<int>& c) { for (auto i : adaptor<int>{c}) // <- init { /* ... */ } } 

It was fine and compiled without warning using GCC-4.7.0.

Then I became curious to initialize POD and what could change with C ++ 0x. There I found the Bjarnes FAQ . He says that PODs can contain pointers , but not references .

Ops, now I'm wondering:

  • I have a non-POD object here that the compiler can initialize without a constructor anyway , and I just skip what mechanisms are used here?
  • or Is GCC-4.7.0 a non-std host , allowing me to initialize ref this way?
  • or has there been a change in std from Bjarnes FAQ, which also allows you to link to POD?

Update: I found aggregates in the current std (8.5.1 Aggregates [dcl.init.aggr]), but the links are not mentioned there, so I'm not sure how they relate to this

+4
source share
1 answer

Quoting the standard [dcl.init.aggr]:

An aggregate is an array or class (section 9) without any custom constructors (12.1), no logical or asymmetric initializers for non-static data members (9.2), no private or protected non-static data (Section 11), no base classes (section 10 ) and there are no virtual functions (10.3).

When an aggregate is initialized by the list of initializers, as specified in 8.5.4, the elements of the list of initializers are taken as initializers for the members of the aggregate, increasing the index or the order of the members. Each member is initialized with a copy from the corresponding initializer -... clause

This means that you have an aggregate here, aggregates can be initialized as you do. PODs have nothing to do with it, they are really intended for communication, for example. WITH.

Copying-initializing a link with a variable is definitely legal, because it just means

 T& ref = c; 

I have a non-POD object here that the compiler can initialize without a constructor, and I just skip what mechanisms are used here?

Yes, the object is not a POD.

Is GCC-4.7.0 a non-std host, allowing me to initialize ref this way?

No.

+4
source

Source: https://habr.com/ru/post/1369291/


All Articles