C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Let constructor know if object is const or volatile

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Thu, 28 Sep 2023 20:46:40 +0100
On Thu, 2023-09-28 at 11:50 +0100, Frederick Virchanza Gotham via Std-
Proposals wrote:
> Consider the following code snippet:
>
> #include <iostream> // cout, endl
> #include <type_traits> // is_const, remove_pointer
>
> struct Monkey {
> int i;
> void NonConst(void) { i = 7; }
> Monkey(void)
> {
> this->NonConst(); // 'this' must be a pointer to non-const
> here
>
> if ( std::is_const_v< std::remove_pointer_t<decltype(this)> >
> )
> {
>   std::cout << "This is a const object\n";
>         }
>     }
> };
>
> int main(void)
> {
>     Monkey obj1;
> Monkey const obj2;
> }
>
> This code snippet doesn't print "This is a const object" because
> 'this' is a pointer to non-const inside the constructor.
>
> Perhaps we could have an implicit type inside every constructor,
> something like "_This_t" to be used as followed:
>
>     Monkey::Monkey(void)
>     {
>         this->NonConst();    // 'this' must be a pointer to non-const
> here
>
> if ( std::is_const_v< std::remove_pointer_t<_This_t> > )
> {
> std::cout << "This is a const object\n";
> }
> }

I don't think the mechanism you propose could work, however adding this
capability in a different way was proposed before in the context of
non-transient constexpr allocations:

https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1974r0.pdf#section.8

Cheers,
Lénárd

Received on 2023-09-28 19:46:45