我了解将 static_pointer_cast 与 unique_ptr 一起使用会导致所包含数据的共享所有权。 换句话说,我想做的是: {代码...} 无论如何,这样做会导致两个 unique_ptr 永远不应该同时存在,所以它只是被禁止的。 是...
template<typename Derived, typename Base, typename Del> std::unique_ptr<Derived, Del> static_unique_ptr_cast(std::unique_ptr<Base, Del> && p) { auto d = static_cast<Derived *>(p.release()); return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter())); } Run Code Onli...
"not null" : "null") << std::endl; std::cout << "res2 is " << (static_cast<bool>(res2) ? "not null" : "null") << std::endl; // res2 = res1; // Won't compile: copy assignment is disabled res2 = std::move(res1); // res2 assumes ownership, res1 is set to n...
例如: struct A { operator bool() const { return true; } }; struct B { explicit operator bool() const { return true; }; int main() { A a1; bool na1 = a1; // OK: copy-initialization selects A::operator bool() bool na2 = static_cast<bool>(a1); // OK: static_cast performs...
ptr_); } T &operator*() const { return *ptr_; } T *operator->() const noexcept { return ptr_; } operator bool() const noexcept { return static_cast<bool>(ptr_); } private: T *ptr_{nullptr}; }; template <typename T, typename... Args> auto make_Unique(Args &&...args) {...
()boolna2 = static_cast<bool>(a1);// OK: static_cast performs direct-initializationB b2;if(b2) ;// OK: B::operator bool()// bool nb1 = b2; // error: copy-initialization does not consider B::operator bool()boolnb2 = static_cast<bool>(b2);// OK: static_cast performs direct-...
unique_ptr<Derived> ptr = static_cast<unique_ptr<Derived>>(DerivedAFactory()); 我正在考虑通过从中释放对象来实现此目的unique_ptr,然后使用一个转换原始指针并将其重新分配给其他unique_ptr所需样式的release函数(在调用之前,调用方将显式完成此操作): ...
Interface* object = factory->CreateObject([parameter specifies type ConcreteA]); ... static_cast<ConcreteA*>(object)->FuncOnA(); Run Code Online (Sandbox Code Playgroud) 在这种情况下,您可以通过简单地使用 来避免 RTTI 的复杂性static_cast。
要对保存在shared_ptr里的指针执行static_cast,我们可以取出指针然后强制转换它,但我们不能把它存到另...
shared_ptr的类型转换不能使用一般的static_cast,这种方式进行的转换会导致转换后的指针无法再被shared_ptr对象正确的管理。应该使用专门用于shared_ptr类型转换的 static_pointer_cast<T>() , const_pointer_cast<T>() 和dynamic_pointer_cast<T>()。