What is the preferred way to distribute member data in a C ++ class?

Let's say I have a class that allocates some arbitrary element data. There are two common ways I've seen (I know there are others):

class A
{
    public:
        A();
        ~A();

        //Accessors...
    private:
        B *mB;
}

A::A()
{
    mB = new B();
}

A::~A()
{
    delete B;
}

Versus ...

class A
{
    public:
        //Accessors...
    private:
        B mB;
}

Assume that A itself is allocated on the heap by the consumer code.

In general, which method is preferred? I understand that specific situations really encourage this or that, but in the absence of these requirements is one way? What are the tradeoffs?

+3
source share
4 answers

. new/delete, , , , . ++ , IMHO

+9

.

, B , B, B. , B A (f'rinstance, A swap B), .

. , A.hh , B (.. A.h #include "B.hh"), , A.hh, B.hh.

- , , , , . ; , .

+4

, ( ). , , .

, PIMPL, ( ). (, boost::shared_ptr) .

0

, , , .

: . .

( , , ..).

:

, ( , pimpl ..)

0

Source: https://habr.com/ru/post/1762679/


All Articles