Allocating Arrays with Placement new

Allocating Arrays with Placement new

llocating objects on a predetermined memory address has become a popular idiom in recent years, particularly in mobile programming, embedded systems, and custom garbage collectors. However, the technique shown in my debut 10-Minute Solution covers only scalar objects. Many readers have asked me whether it’s possible to use a similar technique for allocating arrays as well. The answer is of course “yes.” Here’s how.


How can you allocate arrays of objects on a predetermined memory address?


Use placement new with a twist.

Good Ol’ new
Before discussing array allocations, let’s remind ourselves the basics i.e., how to use placement new. The scalar (i.e. non-array) version placement new takes a user-supplied address on which it constructs an object. Unlike the ordinary new operator, placement new doesn’t allocate storage for the object; it merely constructs it on the memory address given. Here’s an example:

#include  //required for using placement newclass Widget {..};char* buff=new char [sizeof (Widget)];//preallocate storageWidget* pw= new(buff) Widget; //construct Widget on buffpw->Draw(); //use Widget

The destruction of such an object consists of two steps. First, invoke its destructor explicitly:

pw->~Widget(); //explicit destructor invocation

Then, reclaim the raw memory:

delete[] buff;

Array Allocation
Array allocation requires the same steps, albeit with some subtle differences. First, allocate a buffer large enough to hold an array of the desired type:

const int ARRSIZE=5;char * buff=new [sizeof(Widget)*ARRSIZE]; 

Next, construct an array of ARRSIZE objects on the buffer using placement new []:

Widget* pw=new(buff) Widget[ARRSIZE];//construct an array

You can now use this array as usual:

for (int i=0; i

Note: Remember that in order to create an array of X, class X must have an accessible default constructor.

Array Destruction
To destroy such an array, call each element's destructor explicitly:

int i=ARRSIZE;while (i) pw[--i].~Widget()

Notice that the while-loop uses a descending order to preserve the canonical destruction order of C++: the array element with the highest index is destroyed first, because it was constructed last.

Performance Refinements
Placement new[] has a potential performance problem. It initializes every element in the array. When dealing with large arrays, this isn't efficient. In some applications, only a portion of the array is actually used, or the elements are assigned a different value immediately after construction. In such cases, you want to defer (or completely elide) the initialization of array elements. This is possible but requires additional maneuvers.

As usual, start by allocating a raw buffer with the appropriate size. This time however, use the global operator new:

Widget * warr= static_cast  (::operator new ( sizeof(Widget)* ARRSIZE));

The global operator new, very much like C's malloc(), merely allocates raw bytes of memory from the free-store, without initialization. It returns void *, which has to be explicitly cast to a typed pointer using static_cast.

You're probably wondering why I use the global operator new instead of:

new char[sizeof(Widget)*ARRSIZE); //works but not recommended

Although this syntax works too, it would force you to use reinterpret_cast instead of static_cast to convert char * to Widget *.As a rule, prefer static_cast when possible.

At this stage, warr is actually a pointer to raw memory. You can't access its elements because they haven't been initialized yet. To initialize individual elements, call placement new once more, like this:

void assign(Widget arr[],             size_t & sz,             const Widget& initval){ new (&arr[sz++]) Widget (initval); //invoke copy ctor}

How does it work? assign() passes the address of an array element to placement new which invokes Widget's copy constructor, initializing that element with initval. This method enables you to initialize elements selectively, leaving the rest of the array uninitialized. The elements within the range arr[sz]..arr[last] aren't initialized.

To destroy such an array, invoke the destructor of every initialized object. Then call the global operator delete to reclaim the raw storage:

void destroy(Widget arr[], size_t & sz){ while (sz)  arr[--sz].~Widget();//destroy all initialized elements ::operator delete (arr); //reclaim raw storage}

As Good as new
The techniques shown here are quite dangerous. Therefore, they should be encapsulated in higher-level classes that hide the implementation details from users. STL allocators are a good example of this design practice. Under the hood, they use similar techniques to elide object initialization, minimize reallocations, and speed up allocations.

devx-admin

devx-admin

Share the Post:
AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to

AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at business finance firm Brex, Schirano

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using Meta’s Llama 2 model, serves

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations and emerging startups in areas

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by

What You Need to Know About Cloud Security Strategies

What You Need to Know About Cloud Security Strategies

Today, many businesses are adopting cloud computing services. As a result, it’s important to recognize that security measures for data in the cloud are different from those in traditional on-premises

Romanian Energy Security

Eastern Europe is Achieving Energy Security

Canada and Romania have solidified their commitment to energy security and independence from Russian energy exports by signing a $3-billion export development agreement. The deal is centered on constructing two

Seamless Integration

Unlocking Seamless Smart Home Integration

The vision of an intelligently organized and interconnected smart home that conserves time, energy, and resources has long been desired by many homeowners. However, this aspiration has often been hindered

New Algorithm

MicroAlgo’s Groundbreaking Algorithm

MicroAlgo Inc. has revealed the creation of a knowledge-augmented backtracking search algorithm, developed through extensive research in evolutionary computational techniques. The algorithm is designed to boost problem-solving effectiveness, precision, and

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a