为什么make_unique调用编译?make_unqiue不要求其模板参数是完整类型吗?
struct F;
int main()
{
std::make_unique<F>();
}
struct F {};
Run Code Online (Sandbox Code Playgroud)
在从orignated问题我的"问题"与我PIMPL实现:
我确实理解为什么析构函数必须在用户声明并在实现类(PIMPL)的cpp文件中定义.
但是移动包含pimpl的类的构造函数仍会编译.
class Object
{};
class CachedObjectFactory
{
public:
CachedObjectFactory();
~CachedObjectFactory();
std::shared_ptr<Object> create(int id) const;
private:
struct CacheImpl;
std::unique_ptr<CacheImpl> pImpl;
};
Run Code Online (Sandbox Code Playgroud)
现在cpp文件:
// constructor with make_unique on incompete type ?
CachedObjectFactory::CachedObjectFactory()
: pImpl(std::make_unique<CacheImpl>())
{}
struct CachedObjectFactory::CacheImpl
{
std::map<int, std::shared_ptr<Object>> idToObjects;
};
//deferred destructor
CachedObjectFactory::~CachedObjectFactory() = default;
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么这个编译?为什么建筑和破坏之间存在差异?如果析构函数的实例化和default_deleter的实例化是一个问题,为什么make_unique的实例化不是问题?
如果完全定义了类型,是否可以使用SFINAE进行检查?
例如
template <class T> struct hash;
template <> struct hash<int> {};
// is_defined_hash_type definition...
enum Enum { A, B, C, D };
static_assert ( is_defined_hash_type<int> ::value, "hash<int> should be defined");
static_assert (! is_defined_hash_type<Enum>::value, "hash<Enum> should not be defined");
Run Code Online (Sandbox Code Playgroud)
解决方案不应该修改哈希结构.
假设我有一些不完整的类型
// in foo.hh
struct Hidden;
Run Code Online (Sandbox Code Playgroud)
我想用作 a 的元素类型std::vector。使用unionI 可以“推迟”对构造函数和析构函数的调用以std::vector实现联合构造函数/析构函数。
// in foo.hh
struct Public {
union Defer {
std::vector<Hidden> v;
Defer();
// add copy/move constructor if needed
~Defer();
} d;
};
Run Code Online (Sandbox Code Playgroud)
现在我只能Public通过包含foo.hh和链接实现Public::Defer::Defer()和的文件来使用Public::Defer::~Defer()。只有那些需要访问Hidden.
这是合法的 C++ 吗?如果有,从什么时候开始?
背景:我在回答另一个问题时提出的问题。