此代码产生警告:“声明需要全局构造函数[-Wglobal-constructors]”
// Compile with -Wglobal-constructors
class T {
public:
constexpr T(int* p) : ptr_(p) {}
T(const T& other) : T(other.ptr_) {}
private:
int* ptr_;
};
struct MyStruct {
int x;
T y;
};
MyStruct s[] {{ 123, nullptr },{ 234, nullptr }};
我以为添加constexpr T(std::nullptr_t) : ptr_(nullptr) {}
会解决这个问题,但是没有。取而代之的是使复制构造函数constexpr
生效,这使我感到困惑。如果有的话,同样适用于move构造函数。
结果表明,此行为一直持续到C ++ 14,但在C ++ 17中不再适用,复制省略涵盖了这种情况。