有这个代码:
struct Vec3 {
int x;
int y;
int z;
};
template <typename T>
class myProperty {
public:
myProperty(const T& initValue) : m_value{initValue} {}
private:
T m_value;
};
Run Code Online (Sandbox Code Playgroud)
创建myProperty类型对象时:
myProperty<int> ip{1};
myProperty<Vec3> vp1{{1, 2, 3}};
// myProperty<Vec3> vp2{1, 2, 3}; ERROR: myProperty doesn't have a matching constructor.
Run Code Online (Sandbox Code Playgroud)
是否有一种优雅的vp2初始化工作方式?专业myProperty的Vec3是矫枉过正.
如何强制编译器使类的默认析构函数非内联?
这样做的一种方法是编写一个空的析构函数定义,但它感觉很乱,而且你从静态分析器得到一个警告(在我的情况下是clang-tidy),= default应该用于一个简单的析构函数.
要详细说明实际用例 - 目标是使用类似的东西:
MyClass.h
class MyClassImpl;
class MyClass {
std::unique_ptr<MyClassImpl> m_impl;
public:
MyClass();
// and some other methods
};
Run Code Online (Sandbox Code Playgroud)
A std::unique_pointer到不完整类型,在标头中向前声明,定义仅在源文件中已知.
上面的代码会给出编译器错误:
error: use of undefined type 'MyClassImpl'
Run Code Online (Sandbox Code Playgroud)
实际问题是,MyClass编译器生成的默认析构函数是内联的,因此它需要完整的类型信息MyClassImpl.
这可以通过添加一个空的析构函数来修复MyClass(通过在头文件中声明并在源文件中定义,因为在头文件中定义将隐式地使其内联,这将导致相同的错误).
但这是现代C++中唯一的方法吗?
c++ ×2
c++11 ×1
c++14 ×1
clang-format ×1
class ×1
constructor ×1
destructor ×1
inline ×1
templates ×1
unique-ptr ×1