Adhering to constant correctness, you can make your local object of type unique_ptr
const as follows, whereas it T
is some kind of unimportant type:
unique_ptr<T> foo() {
const unique_ptr<T> p = make_unique<T>(...);
... using p pointee ...
return p;
}
Unfortunately, it does not compile because the return value cannot be initialized because it unique_ptr
does not have a copy constructor, and the move constructor is not possible, since it p
is a constant.
How about whether the C ++ standard says that when the “operand” of the return statement is an automatic object, its potential constant should be ignored? An automatic object cannot be referenced after initializing the return value, so its constant does not matter now. The const object can also be modified in its destructor, so it really just determines where constness ends: immediately before the destructor or, in this special case, before the constructor of the return value.
However, “cannot be referenced” is not the whole truth: destructors of other locales that are sequenced after initializing the return value can refer to it. But I think it is impossible for them to take care that the const object is changed. They recognized the object through a pointer or a reference to const, i.e. From their point of view, they only know that they are not allowed to change it, they cannot know whether others are allowed to change it.
Do you think that such a change in the C ++ standard would be a good idea? Or do you see other solutions next to what I gave below?
For write only: Non-solutions and other solutions:
- You cannot
return unique_ptr<T>(p.get())
, because now you have two unique_ptr
s, each of which considers it to be a unique owner. return unique_ptr<T>(p.release())
, p
, release()
- .return move(p)
, , , - .- : ,
return const_cast<unique_ptr<T>&&>(p)
, const - undefined (7.1.6.1 p4 N4140).