简体   繁体   English

我应该创建一个临时对象来实例化C ++中的成员变量吗?

[英]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 ? 当我只有t时,实例化B的正确方法是什么? Should I create a temporary variable of type A like: 我应该创建一个类型为A的临时变量,例如:

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 : 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 . 您正在创建一个临时文件,并使用其地址并将地址添加到_a Once B 's constructor finishes, the temporary will go out of scope and _a still point to an invalid object. 一旦B的构造函数完成,该临时对象将超出范围,并且_a仍指向无效的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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