blob: 15408bcfd7afa80389044cb5e334137811850e42 [file] [log] [blame]
[email protected]a1683a12014-01-08 21:38:301// Copyright 2014 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// This file contains macros and macro-like constructs (e.g., templates) that
6// are commonly used throughout Chromium source. (It may also contain things
7// that are closely related to things that are commonly used that belong in this
8// file.)
9
10#ifndef BASE_MACROS_H_
11#define BASE_MACROS_H_
12
13#include <stddef.h> // For size_t.
14#include <string.h> // For memcpy.
15
[email protected]a1683a12014-01-08 21:38:3016// Put this in the private: declarations for a class to be uncopyable.
17#define DISALLOW_COPY(TypeName) \
18 TypeName(const TypeName&)
19
20// Put this in the private: declarations for a class to be unassignable.
21#define DISALLOW_ASSIGN(TypeName) \
22 void operator=(const TypeName&)
23
24// A macro to disallow the copy constructor and operator= functions
25// This should be used in the private: declarations for a class
26#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
27 TypeName(const TypeName&); \
28 void operator=(const TypeName&)
29
30// An older, deprecated, politically incorrect name for the above.
31// NOTE: The usage of this macro was banned from our code base, but some
32// third_party libraries are yet using it.
33// TODO(tfarina): Figure out how to fix the usage of this macro in the
34// third_party libraries and get rid of it.
35#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName)
36
37// A macro to disallow all the implicit constructors, namely the
38// default constructor, copy constructor and operator= functions.
39//
40// This should be used in the private: declarations for a class
41// that wants to prevent anyone from instantiating it. This is
42// especially useful for classes containing only static methods.
43#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
44 TypeName(); \
45 DISALLOW_COPY_AND_ASSIGN(TypeName)
46
47// The arraysize(arr) macro returns the # of elements in an array arr.
48// The expression is a compile-time constant, and therefore can be
49// used in defining new arrays, for example. If you use arraysize on
50// a pointer by mistake, you will get a compile-time error.
[email protected]a1683a12014-01-08 21:38:3051
52// This template function declaration is used in defining arraysize.
53// Note that the function doesn't need an implementation, as we only
54// use its type.
55template <typename T, size_t N>
56char (&ArraySizeHelper(T (&array)[N]))[N];
57
58// That gcc wants both of these prototypes seems mysterious. VC, for
59// its part, can't decide which to use (another mystery). Matching of
60// template overloads: the final frontier.
61#ifndef _MSC_VER
62template <typename T, size_t N>
63char (&ArraySizeHelper(const T (&array)[N]))[N];
64#endif
65
66#define arraysize(array) (sizeof(ArraySizeHelper(array)))
67
[email protected]a1683a12014-01-08 21:38:3068
69// Use implicit_cast as a safe version of static_cast or const_cast
70// for upcasting in the type hierarchy (i.e. casting a pointer to Foo
71// to a pointer to SuperclassOfFoo or casting a pointer to Foo to
72// a const pointer to Foo).
73// When you use implicit_cast, the compiler checks that the cast is safe.
74// Such explicit implicit_casts are necessary in surprisingly many
75// situations where C++ demands an exact type match instead of an
76// argument type convertible to a target type.
77//
78// The From type can be inferred, so the preferred syntax for using
79// implicit_cast is the same as for static_cast etc.:
80//
81// implicit_cast<ToType>(expr)
82//
83// implicit_cast would have been part of the C++ standard library,
84// but the proposal was submitted too late. It will probably make
85// its way into the language in the future.
86template<typename To, typename From>
87inline To implicit_cast(From const &f) {
88 return f;
89}
90
91// The COMPILE_ASSERT macro can be used to verify that a compile time
92// expression is true. For example, you could use it to verify the
93// size of a static array:
94//
viettrungluueb552d72014-10-14 01:40:0295// COMPILE_ASSERT(arraysize(content_type_names) == CONTENT_NUM_TYPES,
[email protected]a1683a12014-01-08 21:38:3096// content_type_names_incorrect_size);
97//
98// or to make sure a struct is smaller than a certain size:
99//
100// COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
101//
102// The second argument to the macro is the name of the variable. If
103// the expression is false, most compilers will issue a warning/error
104// containing the name of the variable.
105
106#undef COMPILE_ASSERT
[email protected]a1683a12014-01-08 21:38:30107#define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg)
108
[email protected]a1683a12014-01-08 21:38:30109// bit_cast<Dest,Source> is a template function that implements the
110// equivalent of "*reinterpret_cast<Dest*>(&source)". We need this in
111// very low-level functions like the protobuf library and fast math
112// support.
113//
114// float f = 3.14159265358979;
115// int i = bit_cast<int32>(f);
116// // i = 0x40490fdb
117//
118// The classical address-casting method is:
119//
120// // WRONG
121// float f = 3.14159265358979; // WRONG
122// int i = * reinterpret_cast<int*>(&f); // WRONG
123//
124// The address-casting method actually produces undefined behavior
125// according to ISO C++ specification section 3.10 -15 -. Roughly, this
126// section says: if an object in memory has one type, and a program
127// accesses it with a different type, then the result is undefined
128// behavior for most values of "different type".
129//
130// This is true for any cast syntax, either *(int*)&f or
131// *reinterpret_cast<int*>(&f). And it is particularly true for
132// conversions between integral lvalues and floating-point lvalues.
133//
134// The purpose of 3.10 -15- is to allow optimizing compilers to assume
135// that expressions with different types refer to different memory. gcc
136// 4.0.1 has an optimizer that takes advantage of this. So a
137// non-conforming program quietly produces wildly incorrect output.
138//
139// The problem is not the use of reinterpret_cast. The problem is type
140// punning: holding an object in memory of one type and reading its bits
141// back using a different type.
142//
143// The C++ standard is more subtle and complex than this, but that
144// is the basic idea.
145//
146// Anyways ...
147//
148// bit_cast<> calls memcpy() which is blessed by the standard,
149// especially by the example in section 3.9 . Also, of course,
150// bit_cast<> wraps up the nasty logic in one place.
151//
152// Fortunately memcpy() is very fast. In optimized mode, with a
153// constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
154// code with the minimal amount of data movement. On a 32-bit system,
155// memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
156// compiles to two loads and two stores.
157//
158// I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
159//
160// WARNING: if Dest or Source is a non-POD type, the result of the memcpy
161// is likely to surprise you.
162
163template <class Dest, class Source>
164inline Dest bit_cast(const Source& source) {
165 COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), VerifySizesAreEqual);
166
167 Dest dest;
168 memcpy(&dest, &source, sizeof(dest));
169 return dest;
170}
171
172// Used to explicitly mark the return value of a function as unused. If you are
173// really sure you don't want to do anything with the return value of a function
174// that has been marked WARN_UNUSED_RESULT, wrap it with this. Example:
175//
176// scoped_ptr<MyType> my_var = ...;
177// if (TakeOwnership(my_var.get()) == SUCCESS)
178// ignore_result(my_var.release());
179//
180template<typename T>
181inline void ignore_result(const T&) {
182}
183
184// The following enum should be used only as a constructor argument to indicate
185// that the variable has static storage class, and that the constructor should
186// do nothing to its state. It indicates to the reader that it is legal to
187// declare a static instance of the class, provided the constructor is given
188// the base::LINKER_INITIALIZED argument. Normally, it is unsafe to declare a
189// static variable that has a constructor or a destructor because invocation
190// order is undefined. However, IF the type can be initialized by filling with
191// zeroes (which the loader does for static variables), AND the destructor also
192// does nothing to the storage, AND there are no virtual methods, then a
193// constructor declared as
194// explicit MyClass(base::LinkerInitialized x) {}
195// and invoked as
196// static MyClass my_variable_name(base::LINKER_INITIALIZED);
197namespace base {
198enum LinkerInitialized { LINKER_INITIALIZED };
199
200// Use these to declare and define a static local variable (static T;) so that
201// it is leaked so that its destructors are not called at exit. If you need
202// thread-safe initialization, use base/lazy_instance.h instead.
203#define CR_DEFINE_STATIC_LOCAL(type, name, arguments) \
204 static type& name = *new type arguments
205
206} // base
207
208#endif // BASE_MACROS_H_