Search code examples
c++c++11destructorconstexprweak-ptr

Constructing a constexpr std::weak_ptr


According to the std::weak_ptr documentation one can construct a constexpr weak_ptr:

#include <memory>
constexpr weak_ptr<int> foo{};

However, trying this with clang produces a compilation error complaining that a constexpr variable cannot have non-literal type 'const std::weak_ptr<int>', which is because weak_ptr<int> has a user-provided destructor. (which is does, looking at the libc++ headers)

My question is, is this a libc++ bug, or do constexpr weak_ptr just make no sense and having the constexpr default constructor is a mistake? Can I expect this to work in the future?


Solution

  • is this a libc++ bug

    No.

    Do constexpr weak_ptr just make no sense

    Yes.

    having the constexpr default constructor is a mistake?

    No. A constexpr constructor used on a non-literal type permits constant initialization for static and thread storage duration variables, which takes place before any dynamic initialization.

    This means, for instance, that a global default-constructed weak_ptr object is always initialized, and can safely be used in constructors of global objects.

    // TU 1
    namespace foo {
       std::weak_ptr<int> meow;
    }
    
    // TU 2
    namespace foo {
       extern std::weak_ptr<int> meow;
    }
    
    struct C {
        C() { /* can safely use foo::meow here */ }
    } c;
    

    Can I expect this [constexpr weak_ptr] to work in the future?

    No.