The initialization of the return value must ignore the constant of the automatic object

Adhering to constant correctness, you can make your local object of type unique_ptrconst as follows, whereas it Tis 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_ptrdoes not have a copy constructor, and the move constructor is not possible, since it pis 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_ptrs, 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).
+4
2

unique_ptr - , () . , const.

, ++ 17 " elision" (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html) . , , , const unique_ptr. , ,

+4

, . , , , .

, , const .

, . unique_ptr const, , , - . , :

std::unique_ptr<T> foo()
{
    // const object means no calling non-const member functions
    // which means no changing the ownership of the managed pointer
    const std::unique_ptr<int> p = std::make_unique<int>();

    // but we still get to manipulate the thing being pointed to:
    *p = 6;

    return std::move(p); // compile error - changing ownership
}

unique_ptr const, unique_ptr, do . unique_ptr const . , unique_ptr const, , .

, const .

+2

Source: https://habr.com/ru/post/1628218/


All Articles