OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 // AlignedMemory and RawAlignedMemory give you portable ways to specify aligned |
| 6 // static or local stack data. For example, if you need static storage for a |
| 7 // class, but you want manual control over when the object is constructed and |
| 8 // destructed (you don't want static initialization and destruction), use |
| 9 // AlignedMemory: |
| 10 // |
| 11 // static AlignedMemory<MyClass> my_class; |
| 12 // |
| 13 // // ... at runtime: |
| 14 // new(my_class.data()) MyClass(); |
| 15 // |
| 16 // // ... later, to destruct my_class: |
| 17 // my_class.data()->MyClass::~MyClass(); |
| 18 // |
| 19 // RawAlignedMemory just contains a uint8 buffer with a specified size and |
| 20 // memory alignment. |
| 21 |
| 22 |
| 23 #ifndef BASE_MEMORY_ALIGNED_MEMORY_H_ |
| 24 #define BASE_MEMORY_ALIGNED_MEMORY_H_ |
| 25 #pragma once |
| 26 |
| 27 #include "base/basictypes.h" |
| 28 #include "base/compiler_specific.h" |
| 29 #include "base/logging.h" |
| 30 |
| 31 namespace base { |
| 32 |
| 33 // RawAlignedMemory is specialized for all supported alignments. |
| 34 // Make sure we get a compiler error if someone uses an unsupported alignment. |
| 35 template <size_t Size, size_t ByteAlignment> |
| 36 struct RawAlignedMemory {}; |
| 37 |
| 38 #define BASE_DECL_RAW_ALIGNED_MEMORY(byte_alignment) \ |
| 39 template <size_t Size> \ |
| 40 class RawAlignedMemory<Size, byte_alignment> { \ |
| 41 public: \ |
| 42 void* void_data() { return reinterpret_cast<void*>(data_); } \ |
| 43 private: \ |
| 44 ALIGNAS(byte_alignment) uint8 data_[Size]; \ |
| 45 void* operator new(size_t size); \ |
| 46 void operator delete(void *ptr); \ |
| 47 } |
| 48 |
| 49 // Specialization for all alignments is required because MSVC (as of VS 2008) |
| 50 // does not understand ALIGNAS(ALIGNOF(Type)) or ALIGNAS(template_param). |
| 51 BASE_DECL_RAW_ALIGNED_MEMORY(1); |
| 52 BASE_DECL_RAW_ALIGNED_MEMORY(2); |
| 53 BASE_DECL_RAW_ALIGNED_MEMORY(4); |
| 54 BASE_DECL_RAW_ALIGNED_MEMORY(8); |
| 55 BASE_DECL_RAW_ALIGNED_MEMORY(16); |
| 56 BASE_DECL_RAW_ALIGNED_MEMORY(32); |
| 57 BASE_DECL_RAW_ALIGNED_MEMORY(64); |
| 58 BASE_DECL_RAW_ALIGNED_MEMORY(128); |
| 59 BASE_DECL_RAW_ALIGNED_MEMORY(256); |
| 60 BASE_DECL_RAW_ALIGNED_MEMORY(512); |
| 61 BASE_DECL_RAW_ALIGNED_MEMORY(1024); |
| 62 BASE_DECL_RAW_ALIGNED_MEMORY(2048); |
| 63 BASE_DECL_RAW_ALIGNED_MEMORY(4096); |
| 64 |
| 65 template <typename Type> |
| 66 class AlignedMemory : public RawAlignedMemory<sizeof(Type), ALIGNOF(Type)> { |
| 67 public: |
| 68 Type* data() { |
| 69 return reinterpret_cast<Type*>(this->void_data()); |
| 70 } |
| 71 }; |
| 72 |
| 73 } // base |
| 74 |
| 75 #endif // BASE_MEMORY_ALIGNED_MEMORY_H_ |
OLD | NEW |