Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 260
clord Avatar asked Feb 07 '23 18:02

clord


1 Answers

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.

like image 133
T.C. Avatar answered Feb 09 '23 09:02

T.C.