C++ Logo

std-proposals

Advanced search

Re: C++ create a class with array members which are notconstructed.

From: Steve Hearnden <steve_at_[hidden]>
Date: Wed, 2 Sep 2020 20:33:20 +0100
Thanks for your replies. I think that std::optional is similar to what I was thinking about, but was requesting an extension to C++ to produce different behaviour.

The implementation of std::optional with my Microsoft compiler has a union which is something like....

union {
     char _Dummy;
     T _Value;
};
This is an excellent example of my use-case. The code in the library has to side-step the behaviour of the compiler of constructing items, and would be replaced by my proposal with ....

[[unconstructed]] _Value;

We would simplify implementations of std::optional, focusing on the behaviour we require, rather than hiding from the compiler the use cases.

The pmr:: (polymorphic-memory-resources) list presented by Jason Turner offers alternative memory stores. Which is for a different problem.

aligned_storage_t performs the same job as I was after, but you are left with a storage space, but would have to cast to the underlying type in order to use the memory. I feel these are creating more awkward code results which is harder to maintain, than the idea of [[unconstructed]], which would help in library implementations.


Sent from Mail for Windows 10

From: Steve Hearnden via Std-Proposals
Sent: 02 September 2020 19:47
To: std-proposals_at_lists.isocpp.org
Cc: Steve Hearnden
Subject: [std-proposals] C++ create a class with array members which are notconstructed.

I was looking at a performance issue, with some code and found that the cost of creating the dynamic heap memory was the significant cost.

It would have been handy to have a class which implemented something like std::vector, but with a *small* buffer of values to use as an alternative piece of memory when the vector size was below a threshold.
Unfortunately, an array of the constructed type, would cause the constructor to be called for each array element, and for complex types, could undo the benefit of the pre-bought memory.

My proposal would be for classes (or structures) to have the ability for a member to be declared with an attribute

[[unconstructed]]
which would cause none of the constructors to actually construct the object.
The class would not naturally also call destructors.

e.g.
template< class T, size_t size>
class temp_vector
{
                [[unconstructed]] T _V[size];
            size_t m_constructed = 0;
public:
                ~temp_vector()
                {
///// Destroy the array manually.
                                for( size_t i = 0; i < m_constructed; i++ ){
                                                _V[i].~T();
}
}
}


Sent from Mail for Windows 10


Received on 2020-09-02 14:38:09