MPD 0.20.6

- Main Page
- Namespaces
- Data Structures
- Files

- File List
- Globals

VarSize.hxx
Go to the documentation of this file.
1 /*
2 * Copyright (C) 2008-2014 Max Kellermann <max.kellermann@gmail.com>
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the
14 * distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
19 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
20 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
27 * OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 #ifndef MPD_VAR_SIZE_HXX
31 #define MPD_VAR_SIZE_HXX
32
33 #include "Alloc.hxx"
34 #include "Compiler.h"
35
36 #include <type_traits>
37 #include <utility>
38 #include <new>
39 #include <cstdlib>
40
52 template<class T, typename... Args>
53 gcc_malloc
54 T *
55 NewVarSize(size_t declared_tail_size, size_t real_tail_size, Args&&... args)
56 {
57 static_assert(std::is_standard_layout<T>::value,
58 "Not standard-layout");
59
60 /* determine the total size of this instance */
61 size_t size = sizeof(T) - declared_tail_size + real_tail_size;
62
63 /* allocate memory */
64 T *instance = (T *)xalloc(size);
65
66 /* call the constructor */
67 new(instance) T(std::forward<Args>(args)...);
68
69 return instance;
70 }
71
72 template<typename T>
73 gcc_nonnull_all
74 void
75 DeleteVarSize(T *instance)
76 {
77 /* call the destructor */
78 instance->T::~T();
79
80 /* free memory */
81 free(instance);
82 }
83
84 #endif
gcc_nonnull_all
#define gcc_nonnull_all
Definition: Compiler.h:122
gcc_malloc
#define gcc_malloc
Definition: Compiler.h:112
Alloc.hxx
Compiler.h
xalloc
gcc_malloc void * xalloc(size_t size)
Allocate memory.
instance
Instance * instance
DeleteVarSize
gcc_nonnull_all void DeleteVarSize(T *instance)
Definition: VarSize.hxx:75
NewVarSize
gcc_malloc T * NewVarSize(size_t declared_tail_size, size_t real_tail_size, Args &&...args)
Allocate and construct a variable-size object.
Definition: VarSize.hxx:55