C++ Logo

std-discussion

Advanced search

Re: objects with no lifetime for validation

From: Federico Kircheis <federico_at_[hidden]>
Date: Sat, 27 May 2023 07:36:57 +0200
On 26/05/2023 23.23, Jens Maurer wrote:
>
> On 26/05/2023 21.30, Federico Kircheis via Std-Discussion wrote:
>> I know that it is not possible to create objects out of thins air:
>>
>> int i = = 42;
>> char buffer[sizeof(int)];
>> std::memcpy(buffer, &i, sizeof(int));
>>
>> int* j = reinterpret_cast<int*>(buffer);
>> *j; // UB, even if *j == i, as j does not point to an int object
>
> This is not accurate since implicit object creation has been introduced.
> Please read [intro.object] in its entirety.

Mhm, I'll check again...

>> But lately I was toying with the following idea
>>
>> Instead of relying on conventions for denoting the state of a variable,
>> I wanted to use a different type.
>
> I think you simply want a validated_string_view that validates upon
> construction from a std::string or const char *.
> Yes, ownership stays with the original string, whose lifetime has to be
> carefully managed.
>
> Jens

Maybe my example was too simplistic, but creating a view_type does not
scale well.

What if your class contains a vector<string>?


struct data{
vector<string> otherdata;
};

// accepts any data
foo(const data&)

// requires that internal data has certain properties
bar(const data&)



Creating a view_data like

struct data_view{
span<string_view> otherdata;
}

wont work, as span<string_view> cannot point to vector<string>

It just came to my mind that it would be possible to misuse volatile


struct data;

// accepts any data
void foo(const volatile data&);

// requires that internal data has certain properties
void bar(const data&);

const data& validate(const volatile data& d){
     /// validata invariant
     return const_cast<const data&>(d);
}

void foo(const volatile data& d){
  //bar(d); // does not compile
  auto& vd = validate(d);
  bar(vd);

}


It works for all types (as long as the variable is not really volatile),
but it has another set of disadvantages...

Received on 2023-05-27 05:37:07