C ++将类的指针分配给unique_ptr或shared_ptr [英] C++ Assigning this pointer of a class to either a unique_ptr or a shared_ptr

查看:107
本文介绍了C ++将类的指针分配给unique_ptr或shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要从其继承的基类,并且在可以声明其任何派生类之前,必须至少声明一个该基类的实例.我正在考虑将基类的this pointer存储到其自己的unique_ptr成员变量中,而不是使用static_ptr.同样,基类将跟踪其派生类的所有实例,直到声明另一个基类为止.这是我的类声明的样子:

I have a base class that I want to inherit from and before any of its derived classes can be declared at least 1 instance of the base class must be declared first. I was thinking about storing the this pointer of the base class into its own member variable of a unique_ptr instead of using a static_ptr. Also the base class will keep track of all instances of its derived classes until another base class is declared. Here is what my class declarations look like:

#include <vector>
#include <map>
#include <memory>
#include <string>

class Parent {
public: {
    enum ChildType {
        CHILD_NONE = 0,
        CHILD_A,
        CHILD_B,
        CHILD_C,
     }; // ChildType

protected:
    ChildType type_; // Type of Child Class when inheritance is used
    std::string childName_; // Name of Child Class when inheritance is used

private:
    const std::string myName_; // Name of this parent class
    bool parentConstructed_ = false; // Flag if this parent was constructed

    const static Parent* s_firstParent_; // static pointer
    std::unique_ptr<Parent>  me_; // Or
    std::shared_ptr<Parent>  me_;

    // Some Typedefs for containers
    typedef std::vector<std::shared_ptr<Parent>> Children;
    typedef std::vector<std::shared_ptr<Parent>> OtherParents;
    typedef std::vector<std::shared_ptr<Parent>> Siblings;

    typedef std::vector<std::string> Names;
    typedef Names ChildrenNames, OtherParentsNames, SiblingsNames;

    // Containers and map associations of names.
    Children children_;
    ChildrensNames namesOfChildren_;
    std::map< ChildrensNames, Children > mapChildren_;

    OtherParents otherParents_;
    OtherParentsNames associatedParentsNames_;
    std::map< OtherParentsNames, OtherParents > mapParents_;

    Siblings siblings_;
    SiblingsNames namesOfSiblings_;
    std::map< SiblingsNames, Siblings > mapSiblings_;

public:
    // This constructor must be called at least once as a base class instantiation
    // Before Any of its derived members can be declared.
    explicit Parent( const std::string& parentName );

    // Other necessary constructors and operators for move semantics
    Parent( Parent &&self );
    Parent& operator=( Parent &transfer );

    Parent( Parent const& ) = delete;
    Parent& operator=( Parent const & ) = delete;

    // Other functions that are part of the public interface that
    // may be overridden by the inherited types
    virtual void printName() const; 
    const std::string& getName() const;

    // Other public methods that are common among all types including
    // derived and base types.

protected:
    // Constructor Signature to be Used for Derived Types
    Parent( const std::string& parentName, std::string& childName, ChildType type );

    // Other Protected Members for use with derived types
};

所有派生类型都将从该基础公开继承,例如:

All derived types will inherit publicly from this base such as:

class ChildA : public Parent {
public:
    ChildA( const std::string& parentName, std::string& myName, ChildType type );
};

我主要考虑使用此类类层次结构的想法如下

The idea I have in mind for using this class hierarchy in my main would be as follows

#include "ChildA.h"
#include "ChildB.h"
#include "ChildC.h"

int main() {
    // If we try to do this:
    ChildA a( std::string( "Parent" ), std::string( "ChildA" ), Parent::ChildType::CHILD_A );
    // The Last parameter would not be needed to be set since that would
    // be done automatically by default for all derived types, but just shown here for demonstrative purposes.

    // This construction of derived type would throw an exception because at
    // least one base was not declared.

    // This must be done first:
    Parent parent( std::string( "Parent1" );
    // Then this would be valid
    ChildA a( std::string( "Parent1" ), std::string( "ChildA" ) );
    ChildB b( std::string( "Parent1" ), std::string( "ChildB" ) );

    // Then if we created a 2nd parent base
    Parent parent2( std::string( "Parent2" );
    // The next set of child classes might be nested under this parent since
    // it is a 2nd instance and the name doesn't match.
    // if one was to call this constructor above as is but passed in 
    // the same string as from a previous instance it would also throw an exception.

    // In this next line of code it would not necessarily be nested automatically
    // to Parent2 because it would check the string name passed in for the
    // parents name and nest it accordingly if it found that string.
    ChildC c( std::string( "Parent1 or 2" ), std::string( "ChildC" ) );          

    return 0;    
}

我确实知道如何使用静态函数创建静态指针,以在应用程序运行时从类中获取此指针,使其仅具有一个实例.我只想知道是否可以使用shared_ptr或unique_ptr代替,并且在成功创建至少一个基本类型的实例之后,首先将(this)指针保存到任一类型的智能指针中?我更喜欢在父类拥有"它自己的指针的地方做一个独特的操作.

I do know how to create a static pointer with a static function to get the this pointer from the class to have only one instance of it during the runtime of the application. I just want to know is there away to use a shared_ptr or a unique_ptr instead and after successfully creating at least one instance of a base type first then saving the (this) pointer into either type of smart pointer? I was preferring to do a unique where the parent class "owns" it's own pointer.

如果您需要更多信息,请告诉我,我将按要求更新此问题,例如显示我的基类的构造函数的定义.

If you need more information please let me know and I'll update this question as requested, such as showing my base class's constructor's definition.

推荐答案

最好的方法是使用 flyweight 模式.

The best you can do is using the flyweight pattern.

您将创建每个类一次(使用std::shared_ptr似乎最明智),但是随后您将使用轻量级类封装代表仅创建一次的类的每个类,即您将创建一个Parent和子类(无继承层次结构),然后将其传递给ParentFlyweight和ChildFlyweight,其中ChildFlyweight从ParentFlyweight继承.

You will create each class once (using std::shared_ptr seems most sensible), but then you will use a lightweight class to encapsulate each class that stands in for the classes you are only creating once i.e. you will create say a Parent and Child class (no inheritance hierarchy) and then pass those to ParentFlyweight and ChildFlyweight where ChildFlyweight inherits from ParentFlyweight.

这篇关于C ++将类的指针分配给unique_ptr或shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆