Skip to content

Commit

Permalink
Implement destroy_n
Browse files Browse the repository at this point in the history
  • Loading branch information
lackhole committed Aug 4, 2024
1 parent a996a11 commit fb46327
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
22 changes: 22 additions & 0 deletions include/preview/__memory/destroy_n.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//
// Created by yonggyulee on 2024. 8. 4.
//

#ifndef PREVIEW_MEMORY_DESTROY_N_H_
#define PREVIEW_MEMORY_DESTROY_N_H_

#include "preview/__memory/addressof.h"
#include "preview/__memory/destroy_at.h"

namespace preview {

template<typename NothrowForwardIterator, typename Size>
constexpr NothrowForwardIterator destroy_n(NothrowForwardIterator first, Size n) {
for (; n > 0; (void)++first, --n)
preview::destroy_at(preview::addressof(*first));
return first;
}

} // namespace preview

#endif // PREVIEW_MEMORY_DESTROY_N_H_
1 change: 1 addition & 0 deletions include/preview/memory.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "preview/__memory/construct_at.h"
#include "preview/__memory/destroy.h"
#include "preview/__memory/destroy_at.h"
#include "preview/__memory/destroy_n.h"
#include "preview/__memory/make_obj_using_allocator.h"
#include "preview/__memory/pointer_traits.h"
#include "preview/__memory/to_address.h"
Expand Down
19 changes: 19 additions & 0 deletions test/memory.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
#include "preview/bit.h"
#include "preview/ranges.h"

namespace ranges = preview::ranges;
namespace views = preview::views;

struct bizarre_object {
int operator&() const {
return 3;
Expand Down Expand Up @@ -109,6 +112,22 @@ TEST(VERSIONED(Memory), destroy_at) {
}
}

TEST(VERSIONED(Memory), destroy_n) {
alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
bool destroyed[8]{};

for (int i = 0; i < 8; ++i)
new(buffer + sizeof(Tracer) * i) Tracer{i, [&](int x) { destroyed[i] = true; }}; //manually construct objects

auto ptr = reinterpret_cast<Tracer*>(buffer);

EXPECT_TRUE(ranges::equal(destroyed, views::repeat(false, 8)));
preview::destroy_n(ptr, 4);
EXPECT_TRUE(ranges::equal(destroyed, views::concat(views::repeat(true, 4), views::repeat(false, 4))));
preview::destroy_n(ptr + 4, 4);
EXPECT_TRUE(ranges::equal(destroyed, views::repeat(true, 8)));
}

template<class Ptr>
struct BlockList
{
Expand Down

0 comments on commit fb46327

Please sign in to comment.