【发布时间】:2016-06-12 04:31:13
【问题描述】:
一些开发人员显式调用构造函数和析构函数来解决一些问题。我知道,这不是一个好习惯,但似乎是为了实现一些场景。
例如,在这篇文章中,Beautiful Native Libraries,作者使用了这种技术。
在下面的代码中,最后可以看出构造函数被显式调用了:
#include <limits>
template <class T>
struct proxy_allocator {
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T *pointer;
typedef const T *const_pointer;
typedef T& reference;
typedef const T &const_reference;
typedef T value_type;
template <class U>
struct rebind {
typedef proxy_allocator<U> other;
};
proxy_allocator() throw() {}
proxy_allocator(const proxy_allocator &) throw() {}
template <class U>
proxy_allocator(const proxy_allocator<U> &) throw() {}
~proxy_allocator() throw() {}
pointer address(reference x) const { return &x; }
const_pointer address(const_reference x) const { return &x; }
pointer allocate(size_type s, void const * = 0) {
return s ? reinterpret_cast<pointer>(yl_malloc(s * sizeof(T))) : 0;
}
void deallocate(pointer p, size_type) {
yl_free(p);
}
size_type max_size() const throw() {
return std::numeric_limits<size_t>::max() / sizeof(T);
}
void construct(pointer p, const T& val) {
new (reinterpret_cast<void *>(p)) T(val);
}
void destroy(pointer p) {
p->~T();
}
bool operator==(const proxy_allocator<T> &other) const {
return true;
}
bool operator!=(const proxy_allocator<T> &other) const {
return false;
}
};
对于像这样的某些场景,可能需要显式调用构造函数和析构函数,但标准是怎么说的:它是未定义的行为,是未指定的行为,是实现定义的行为,还是定义良好?
【问题讨论】:
-
您只需要确保每个对象构造一次并销毁一次
-
请注意,严格来说,您不能“调用构造函数”。构造函数没有名字。它们在对象初始化期间被调用。初始化对象的一种方法是使用
new。new的一种语法是placement new,它在给定位置构造一个对象。
标签: c++ constructor standards destructor