某些开发人员显式调用构造函数和析构函数以获取某些解决方法。我知道,这不是一个好的做法,但似乎是为了实现某些场景。根据C++标准,显式调用构造函数和析构函数是安全的吗?
例如,在本文中,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,它在给定的位置构造一个对象。 – isanae