c++ - 根据 C++ 标准,显式调用构造函数和析构函数是否安全?

标签 c++ constructor standards destructor

一些开发人员显式调用构造函数和析构函数来解决一些问题。我知道,这不是一个好习惯,但似乎是为了实现一些场景。

例如,在本文中,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/

相关文章:

C++:在类 w.r.t. 的 vector 上选择 argmax任意表达

c++ - C++删除器的签名是什么?

php - 关于为更大的开源项目放弃专有框架的思考

c++ - C++ 中 main 的正确声明是什么?

c - 如何实现标准C函数提取?

c++ - 用C++标准库分析Clang线程安全

c++ - 宽度不均匀时纹理缩放错误

c++ - 从其他容器构造的 STL 容器(例如,从 vector 列表)

java - 确定是否由于派生类实例创建而调用构造函数的最佳方法

Java - 第一次使用构造函数 - 作业