On Thu, 26 Jan 2017 19:57:22 -0800 (PST)
T L <tapir....@gmail.com> wrote:

> > It depends. A call to new can (and will, often) give you a pointer
> > to a stack allocated object. If you pass that pointer to something
> > like fmt.Println() you'll see the object escape to the heap, get
> > flagged by -m, and presumably forbidden by -+. 
> >
> 
> so
> 
> new(T)
> 
> is just a sugar of the following one?
> 
> var t T; &t

Sort of yes, but the allocated (pointed at) value will be anonymous
(not contained in any variable).

IIUC, Go compiler makes no distinction between "stack" and "heap"
allocation: you are free to return pointer to a variable which -- in
C -- would be stack-allocated, and the Go compiler will notice the
value of that variable "escapes" its scope and will make sure it will
be heap-allocated (or otherwise preserved).

Allocating a value with new(T) has the similar property: contrary to the
(not overloaded) operator new from C++, calling new() does not mean you
will get a heap-allocated value: if it can be proven to not escape, it
may well be allocated on the stack.

As you can see for yourself, [1] does not in any way mention how
exactly a value is allocated -- just that a pointer to its memory is
returned.

1. https://golang.org/ref/spec#Allocation

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to