Dynamic and non-dynamic class members

In C ++, ff I have a class that should contain an element that can be dynamically allocated and used as a pointer, or not:

class A {
    type a;
};

or

class A {
    A();
    ~A();
    type* a;
};

and in the constructor:

A::A {
    a = new type();
}

and destructor:

A::~A {
    delete a;
}

Are there any advantages or disadvantages to one other than dynamic, requiring more code? Do they behave differently (except for the pointer to be dereferenced) or slower than the other? Which one should I use?

+5
source share
6 answers

There are several differences:

  • , . , type, forward, - ( ). #include .

  • , , ( ), - , .. , , , . .

  • - , . - new , , . " " (, std::auto_ptr), ( delete , ). , , , .

+5

, . , , . , .

, , , . , , , .

0

, .

, . , . . , , , , .

0

, , , . new, ( , )

0

. . , ( ), . , , .

0

If a member variable must live during the lifetime of the object or if its property must be transferred to another object, then the member must be dynamically (heap) allocated using the "new" one. If this is not the case, then often it is the best choice to make it an immediate member of the class, to simplify the code and reduce the load on the memory allocator. Memory allocation is expensive.

0
source

All Articles