const_pointer_cast
描述 (Description)
它返回一个正确类型的sp的副本,其存储的指针const从U *转换为T *。
声明 (Declaration)
以下是std :: const_pointer_cast的声明。
template <class T, class U>
shared_ptr<T> const_pointer_cast (const shared_ptr<U>& sp) noexcept;
C++11
template <class T, class U>
shared_ptr<T> const_pointer_cast (const shared_ptr<U>& sp) noexcept;
参数 (Parameters)
sp - 它是一个共享指针。
返回值 (Return Value)
它返回一个正确类型的sp的副本,其存储的指针const从U *转换为T *。
异常 (Exceptions)
noexcep - 它不会抛出任何异常。
例子 (Example)
在下面的例子中解释了std :: const_pointer_cast。
#include <iostream>
#include <memory>
int main () {
std::shared_ptr<int> foo;
std::shared_ptr<const int> bar;
foo = std::make_shared<int>(100);
bar = std::const_pointer_cast<const int>(foo);
std::cout << "*bar: " << *bar << '\n';
*foo = 200;
std::cout << "*bar: " << *bar << '\n';
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 -
*bar: 100
*bar: 200