Stream: t-libs/wg-allocators

Topic: const fn Box::new(v)


Charles Lew (May 11 2019 at 17:03, on Zulip):

Hello, i've got a question: What will it take to make Box<T, A>::new a const fn?

John Ericson (May 13 2019 at 16:20, on Zulip):

That would probably require at the very least const fn trait methods and a separate AllocConst: Alloc, AllocConst::alloc, and Box::new_cost

gnzlbg (May 14 2019 at 15:00, on Zulip):

@Charles Lew you can't

gnzlbg (May 14 2019 at 15:01, on Zulip):

you need a new method, e.g.,

impl<T, A: const Alloc> Box<T, A> {
    const fn const_new(x: T) -> Self { ... }
}

at least with https://github.com/rust-rfcs/const-eval/pull/8

gnzlbg (May 14 2019 at 15:01, on Zulip):

cc @oli ^^^

gnzlbg (May 14 2019 at 15:02, on Zulip):

In

impl<T, A: Alloc> Box<T, A> {
   fn new(x: T) -> Self { ... }
}

A might be any type that implements Alloc, independently of whether the impl of Alloc for A is const or not.

gnzlbg (May 14 2019 at 15:04, on Zulip):

To allow new to be const fn only when A: const Alloc we would need some form of negative reasoning, such that these two impls do not overlap:

impl<T, A: Alloc + !const Alloc> Box<T, A> { fn new... non const...; }
impl<T, A: const Alloc> Box<T, A> { const fn new...; }

I don't think this feature is being pursued anywhere.

Charles Lew (May 14 2019 at 15:53, on Zulip):

ok. Well i guess maybe people will want const fn Box::new() with system allocator at some point... so, with the ability to specify an extra allocator (handle), will we lose it (maybe permanently)?

oli (May 14 2019 at 15:58, on Zulip):

with https://github.com/rust-lang/rfcs/pull/2632

impl<T, A: Alloc> Box<T, A> {
    const fn new(x: T) -> Self { ... }
}
oli (May 14 2019 at 15:59, on Zulip):

should work, because const fn new will require A: const Alloc if and only if called from a const context

oli (May 14 2019 at 15:59, on Zulip):

there is no const Alloc syntax for bounds

oli (May 14 2019 at 15:59, on Zulip):

if you want to opt-out of the const Alloc requirement even in const contexts, you need to use A: ?const Alloc

Mike Hommey (May 14 2019 at 22:57, on Zulip):

an Alloc provided that allocates in .data (thus... provided by the compiler itself) could be useful for this.

Last update: Nov 15 2019 at 10:45UTC