Date: Mon, 11 Oct 2021 13:50:07 +0200
On 2021-10-11 at 11:51, Anubhav Guleria via Std-Discussion wrote:
> Is it not true that in either way the thread will get penalize for that
> check? In case if the check is done by container an undefined behavior
> could be avoided.
Yes, the cost is there, but only if you think you need it.
If the program flow is such that you *always* push before you pop, there
is no need for the check.
This is similar to accessing a vector
for (size_t i = 0; i != vec.size(); ++i)
vec[i] = some_value;
where there is no need to check every vec[i] for an out of range index,
because how could it be?
Don't do always what is only needed sometimes, or like Bjarne formulated
it "the zero-overhead principle: What you don’t use, you don’t pay for."
>
> On Mon, Oct 11, 2021, 1:18 PM Bo Persson via Std-Discussion
> <std-discussion_at_[hidden]
> <mailto:std-discussion_at_[hidden]>> wrote:
>
> On 2021-10-11 at 08:53, Anubhav Guleria via Std-Discussion wrote:
> > Thanks for clarifying.
> >
> > Any specific reason why container's pop_back method can't check for
> > current size and if it is 0 then make the pop operation a no-op?
>
> That would be a cost that everyone would have to pay, even when you are
> certain that the stack is never empty.
>
> It is also extremely easy for user code to add the check, if and when
> necessary:
>
> if (!s.empty())
> s.pop();
>
>
>
> Is it not true that in either way the thread will get penalize for that
> check? In case if the check is done by container an undefined behavior
> could be avoided.
Yes, the cost is there, but only if you think you need it.
If the program flow is such that you *always* push before you pop, there
is no need for the check.
This is similar to accessing a vector
for (size_t i = 0; i != vec.size(); ++i)
vec[i] = some_value;
where there is no need to check every vec[i] for an out of range index,
because how could it be?
Don't do always what is only needed sometimes, or like Bjarne formulated
it "the zero-overhead principle: What you don’t use, you don’t pay for."
>
> On Mon, Oct 11, 2021, 1:18 PM Bo Persson via Std-Discussion
> <std-discussion_at_[hidden]
> <mailto:std-discussion_at_[hidden]>> wrote:
>
> On 2021-10-11 at 08:53, Anubhav Guleria via Std-Discussion wrote:
> > Thanks for clarifying.
> >
> > Any specific reason why container's pop_back method can't check for
> > current size and if it is 0 then make the pop operation a no-op?
>
> That would be a cost that everyone would have to pay, even when you are
> certain that the stack is never empty.
>
> It is also extremely easy for user code to add the check, if and when
> necessary:
>
> if (!s.empty())
> s.pop();
>
>
>
Received on 2021-10-11 06:50:20