构造一个 constexpr std::weak_ptr
Constructing a constexpr std::weak_ptr
根据 std::weak_ptr
文档可以构造一个 constexpr
weak_ptr
:
#include <memory>
constexpr weak_ptr<int> foo{};
然而,用 clang 尝试这个会产生编译错误,抱怨 constexpr 变量不能有 non-literal 类型 'const std::weak_ptr<int>
',这是因为 weak_ptr<int>
有一个 user-provided 析构函数。 (确实如此,查看 libc++ headers)
我的问题是,这是一个 libc++ 错误,还是 constexpr
weak_ptr
毫无意义并且使用 constexpr 默认构造函数是一个错误?我可以期待它在未来发挥作用吗?
is this a libc++ bug
没有
Do constexpr
weak_ptr
just make no sense
是的。
having the constexpr default constructor is a mistake?
没有。在非文字类型上使用的 constexpr
构造函数允许 constant initialization 用于静态和线程存储持续时间变量,这发生在任何动态初始化之前。
这意味着,例如,全局默认构造的 weak_ptr
对象始终被初始化,并且可以安全地用于全局对象的构造函数。
// 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?
没有
根据 std::weak_ptr
文档可以构造一个 constexpr
weak_ptr
:
#include <memory>
constexpr weak_ptr<int> foo{};
然而,用 clang 尝试这个会产生编译错误,抱怨 constexpr 变量不能有 non-literal 类型 'const std::weak_ptr<int>
',这是因为 weak_ptr<int>
有一个 user-provided 析构函数。 (确实如此,查看 libc++ headers)
我的问题是,这是一个 libc++ 错误,还是 constexpr
weak_ptr
毫无意义并且使用 constexpr 默认构造函数是一个错误?我可以期待它在未来发挥作用吗?
is this a libc++ bug
没有
Do
constexpr
weak_ptr
just make no sense
是的。
having the constexpr default constructor is a mistake?
没有。在非文字类型上使用的 constexpr
构造函数允许 constant initialization 用于静态和线程存储持续时间变量,这发生在任何动态初始化之前。
这意味着,例如,全局默认构造的 weak_ptr
对象始终被初始化,并且可以安全地用于全局对象的构造函数。
// 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?
没有