Home > Backend Development > C++ > Does C 11's `std::vector::resize()` Interface Change Effectively Value-Initialize New Elements?

Does C 11's `std::vector::resize()` Interface Change Effectively Value-Initialize New Elements?

DDD
Release: 2024-12-26 14:11:14
Original
366 people have browsed it

Does C  11's `std::vector::resize()` Interface Change Effectively Value-Initialize New Elements?

Investigating the Behavior of std::vector::resize() and Boost.Container's resize()

In C 03, std::vector::resize() initialized newly allocated elements with copies of the provided value. C 11 introduced overloads to allow value initialization or initialization via copy.

Using Boost.Container's vector, which supports three resize() overloads similar to C 11, a test was conducted to verify the behavior. In C 03 mode, both std::vector and Boost.Container's vector behaved as expected, initializing new elements with zeros.

However, in C 11 mode, both std::vector and Boost.Container's vector still initialized new elements with zeros when using the overload intended for value initialization. This raises the question:

Is the C 11 std::vector::resize() interface change actually effective?

The results suggest that the interface change has not had the intended effect, as new elements are still being initialized in both implementations.

Addendum

To address the limitations of the existing allocator, an alternative allocator adapter has been proposed that provides a safer and more reliable way to achieve value initialization without initializing all types of elements:

template <typename T, typename A=std::allocator<T>>
class default_init_allocator : public A {
  // ... implementation
};
Copy after login

This adapter interposes on construct() calls for value-initialization, transforming them into default-initialization calls. It also correctly handles default-initialization.

The above is the detailed content of Does C 11's `std::vector::resize()` Interface Change Effectively Value-Initialize New Elements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template