- memory[meta header]
- std[meta namespace]
- function template[meta id-type]
- cpp11[meta cpp]
namespace std {
template <class T, class U>
shared_ptr<T> const_pointer_cast(const shared_ptr<U>& r) noexcept; // (1) C++11
template <class T, class U>
shared_ptr<T> const_pointer_cast(shared_ptr<U>&& r) noexcept; // (2) C++20
}
shared_ptr
で管理するインスタンスに対して const_cast
を行う。
-
r
が空であった場合、この関数は空のshared_ptr<T>
を返却する。 -
(1) :
return shared_ptr<T>(r, const_cast<typename shared_ptr<T>::element_type*>(r.get()));
- r.get()[link get.md]
-
(2) :
return shared_ptr<T>(std::move(r), const_cast<typename shared_ptr<T>::element_type*>(r.get()));
- std::move[link /reference/utility/move.md]
- r.get()[link get.md]
shared_ptr<T>(const_cast<T*>(r.get()))
という方法は動作未定義となるので使用しないこと。
投げない
#include <memory>
#include <iostream>
int main()
{
std::shared_ptr<const int> cp(new int(3));
std::shared_ptr<int> p = std::const_pointer_cast<int>(cp);
std::cout << *p << std::endl;
}
- std::const_pointer_cast[color ff0000]
3
- C++11
- Clang, C++11 mode: 3.0
- GCC, C++11 mode: 4.3.6
- ICC: ??
- Visual C++: 2008 (TR1), 2010, 2012, 2013