目录

static_pointer_cast

描述 (Description)

它使用alloc为类型为T的对象分配内存,并构造它将args传递给它的构造函数。 该函数返回shared_ptr类型的对象 拥有并存储指向构造对象的指针。

声明 (Declaration)

以下是std :: static_pointer_cast的声明。

template <class T, class U>
   shared_ptr<T> static_pointer_cast (const shared_ptr<U>& sp) noexcept;

C++11

template <class T, class U>
   shared_ptr<T> static_pointer_cast (const shared_ptr<U>& sp) noexcept;

参数 (Parameters)

sp - 它是一个共享指针。

返回值 (Return Value)

它返回一个正确类型的sp副本,其存储的指针从U *静态地转换为T *。

异常 (Exceptions)

noexcep - 它不会抛出任何异常。

例子 (Example)

在下面的例子中解释了std :: static_pointer_cast。

#include <iostream>
#include <memory>
struct BaseClass {};
struct DerivedClass : BaseClass {
   void f() const {
      std::cout << "Sample word!\n";
   }
};
int main() {
   std::shared_ptr<BaseClass> ptr_to_base(std::make_shared<DerivedClass>());
   std::static_pointer_cast<DerivedClass>(ptr_to_base)->f();
   static_cast<DerivedClass*>(ptr_to_base.get())->f();
}

让我们编译并运行上面的程序,这将产生以下结果 -

Sample word!
Sample word!
↑回到顶部↑
WIKI教程 @2018