简体   繁体   中英

Should I create a temporary object to instantiate member variable in C++?

I have some classes like this:

class A():{
    public:
        A(T t);
};

class B(): {
    public:
        B(T t);
    private:
        A* _a;
};

What is the correct way to instantiate B when I only have t ? Should I create a temporary variable of type A like:

B::B(T t):
    _a( &(A(t)) )
{ ... }

It seems to me that this isn't such a great idea although I can't exactly put my finger on why. Another option (but not too much better):

B::B(T t):
    _a( 0 )
{
    _a = &(A(t)); 
}

Never do this:

&(anything which lives temporarily)

as it will give you a dangling pointer . Why? Because you take the address of something that's about to deleted immediately afterwards.

When doing the following:

_a(new A(t))

you allocate the same object but don't delete it immediately. However, you need to take care to delete it at some point in your program. Usually in the destructor of your class which I don't see (but then take care of the rule of three or make the class non-copyable) or use a smart pointer which will take care of deletion for you.

Example with std::unique_ptr :

class B(): {
    public:
        B(T t) :
           _a(new A(t))
        { ... }

    private:
        std::unique_ptr<A> _a;
};

You are creating a temporary, taking its address and saving the addres in _a . Once B 's constructor finishes, the temporary will go out of scope and _a still point to an invalid object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM