I am wondering why I get an error when compiling:
const std::unique_ptr<int> get() {
return std::make_unique<int>(10);
}
int main() {
const std::unique_ptr<int> value = get();
return EXIT_SUCCESS;
}
I get the following error:
main.cpp: In function ‘int main()’:
main.cpp:10:44: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’
const std::unique_ptr<int> value = get();
It compiles correctly when I remove const
from the get
signature.
Is there any way to return a constant unique_ptr ?
Because the unique_ptr
is constant it can not be moved only copied. And copying a unique_ptr
is not allowed (otherwise it would not be "unique").
If the data pointed to by the pointer should be constant, then use std::unique_ptr<const int>
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.