Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Re)Initializing object without copy constructor in cpp

Tags:

c++

stack

This question is targeted to embedded systems!

I have the following options to initialize an object:

Object* o = new Object(arg);

This puts the object in the heap and returns a pointer to it. I prefer not to use dynamic allocation in embedded software.

Object o = Object(arg);

This creates a new object in the stack and then copies it to object o and removes it after. This can cause stack overflow if the object is big enough to fit in RAM but not in the stack. I have seen this happening with optimization turned off, I haven't explored if it's different with optimization enabled.

Object o(arg);

This creates the object without making a copy, however how can I "initialize" o again?

For embedded I prefer the last option since the heap is not used and there's no temporary object in the stack that can do a stack overflow.

However I am puzzled on how I can reinitialize the object again since:

o.Object(arg)

is not allowed.

I could create a method called init(arg) and call

o.init(arg)

that does the same initialization as Object::Object(arg) but I would prefer not to have to create an extra method with a "non-standard" name I need to remember.

Is there a way to call the constructor of an already created object to reinitialize it again without making a copy?

like image 708
Carlos Avatar asked Jun 01 '26 19:06

Carlos


2 Answers

Consider using placement new on your object's current memory. This will initialize a new object in currently used memory without allocating new memory. That might be a solution for you. For example:

new (&o) Object(args)

Try this:

#include <iostream>

class A
{
public:

    A(int i)
    {
        m_i = i;
    }

    int m_i;
};

int main()
{
    int s = 10;
    int *ps = new (&s) int(100);
    std::cout << *ps;
    std::cout << s;

    A a(5);
    new (&a) A(49);
    std::cout << a.m_i;
}

g++ -std=c++98 main.cpp returns 10010049, which is correct.

like image 148
Pawel Brzezinski Avatar answered Jun 04 '26 07:06

Pawel Brzezinski


You need use placement new and call the object destructor example below

A a = A();//init
a.~A();//clear
new (&a) A();//re init
like image 23
tomer zeitune Avatar answered Jun 04 '26 07:06

tomer zeitune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!