一些开发人员显式调用构造函数和析构函数来解决一些问题。我知道,这不是一个好习惯,但似乎是为了实现一些场景。
例如,在本文中,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 (reinterpret_cast<void *>(p)) T(val);
被称为placement new syntax并用于在 specific memory location 处构造对象,默认行为;如要求在分配器张贴。如果针对特定类型T
重载了placement new,那么它将被调用而不是全局placement new。
破坏这种构造对象的唯一方法是explicitly call the destructor p->~T();
.
使用放置 new 和显式销毁确实需要/允许实现的代码控制对象的生命周期 - 在这种情况下编译器提供的帮助很少;因此,将对象构建在对齐良好且分配充分的位置非常重要。它们经常在分配器中使用,例如在 OP 和 std::allocator
中。 .
关于c++ - 根据 C++ 标准,显式调用构造函数和析构函数是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35694405/