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 ?
std::unique_ptrobject supposed to be constant, or the data pointed to by it?unique_ptrto a non-const object is sometimes used. In general there's nothing weird about const pointers to non-const. If it's wrong to make the pointer point elsewhere but right to mutate the pointed-to object through the pointer, a const pointer to non-const expresses and enforces that. If one follows the somewhat common practice of making most things const except when there's a reason not to, const pointers to non-const objects arise quite often.constpointer in pimpl makes moves/swaps slower than they need to be, but yes, in general there are cases where a const pointer makes sense.unique_ptrto be constant, despite thatconstreturn values are weird enough even before a noncopyable type likeunique_ptris added into the mix, without explaining why you thought you wanted this oddity. I don't feel that 'why can I not do [weird thing without any apparent justification]' questions are useful, otherwise I could spend my whole day inventing and posting them.constpointers are a good idea, at least if one valuesconst-correctness. Sure, if we have full control over the function signature, a reference should be used. However, a trivial example that comes to mind where a pointer is received is a stdlib algorithm likefind_ifover a range in a container holding pointers (reference_wrapperdoesn't seem worth the hassle & should beconstitself anyway!). If the possibility were left of accidentally mutating the pointer within the receiving function, & that happens, it's not going to end well.