move object from heap to stack

monarch_dodra monarchdodra at gmail.com
Wed Sep 19 23:19:26 PDT 2012


On Wednesday, 19 September 2012 at 21:36:56 UTC, Namespace wrote:
> I count it to destroy it if it isn't used anymore.
What I'm saying though is that when your "stacked_obj" goes out 
of scope, it gets destroyed, 100% of the time. The "chunk" 
disappears, along with any object inside it. When that happens, 
it doesn't matter what the count is, whatever is inside chunk 
MUST be destroyed.

> I can remove this behaviour but IMO with this you haven't 
> unnecessary use of stack memory. Am I wrong?
Yes, because all your stacked_obj have a chunk member variable. 
The reference count doesn't change that. When you pass by value, 
a new chunk is created an copied.

Your postblit is weird:
this(this) {
	this._use_counter++;
	this._use_counter = _use_counter;
}
The way postblit works is that first, the "other" is memcopyed 
onto this. Then, postblit modifies the current object. 
"this._use_counter = _use_counter;" makes no sense.

One more thing: You can't memcopy a class from one place to 
another, because you don't know if it has a CC or not. You 
*could* swap the class, which would be safe for the class itself, 
but not for anything else referencing the class.

> Furthermore, if I copy the stack object e.g. if I pass it as 
> value parameter to another function/class, I can store it as 
> long as it's needed. Maybe that should be the task of the heap, 
> but I'm not sure.
Yes, but technically, you are still passing a copy.

Anyways, I re-read scoped's implementation, and classes ARE 
allocated on the stack. Further more, they can emplace their new 
object.

They can also copy an existing class into them... provided the 
class gives access to CC. It is not a move, but, IMO, a move 
would be unsafe anyways.

import std.typecons;

class A
{
     this(){}
     this(int){}
     this(A){}
}

void main()
{
     auto sa = scoped!A(new A());
     auto sb = scoped!A(5);
}

I'm not entirely.


More information about the Digitalmars-d-learn mailing list