views:

45

answers:

1

Hi,

I am currently working on some simple custom allocators in c++ which generally works allready. I also overloaded the new/delete operators to allocate memory from my own allocator. Anyways I came across some scenarios where I don't really know where the memory comes from like this:

    void myFunc(){
          myObj testObj();
          ....do something with it
    }

In this case testObj would only be valid inside the function, but where would its memory come from? Is there anyway I could link it to my allocator? Would I have to create to object using new and delete or is there another way?

Thanks

+4  A: 

(myObj testObj(); declares a function named testObj which returns a myObj. Use myObj testObj; instead.)

The memory comes from the stack. It will be auto-matically destroyed when leaving the scope.


To use your new and delete you must of course call new and delete:

myObj* p_testObj = new myObj;
...
delete p_testObj;

But allocation on stack is the most efficient since it just involves 1 instruction sub esp, ??. I don't see a reason to use custom allocation unless myObj is huge.

KennyTM
Isn't having those parenthesis after testObj just as valid?
Matti Virkkunen
I am just asking because I want to allocate all my memory in one place.- I propably will use new/delete then. and what I wrote is not a function but a simple call to the constructor :)
@Matti: yes, but not what you want: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.2
KennyTM
as far as I know its just a call to the constructor? or would it need arguments?
@user: `myObj testObj;` reserves memory on the stack, then call the default constructor.
KennyTM
well I am just confused since you can also call an objects constructor like this std::string _str("I am A String");
@user: That's because you have 1 argument to pass, and a function prototype would look have a type e.g. `std::string f(std::string)`, so there's no way the constructor syntax be confused as function declaration.
KennyTM
Thanks, I just checked it myselft, and now that I think about it, it makes sense!