C ++ Atribuindo esse ponteiro de uma classe a um unique_ptr ou shared_ptr
Eu tenho uma classe base que desejo herdar e antes que qualquer uma de suas classes derivadas possa ser declarada, pelo menos 1 instância da classe base deve ser declarada primeiro. Eu estava pensando em armazenar othis pointer
da classe base em sua própria variável de membro de um unique_ptr em vez de usar umstatic_ptr
. Além disso, a classe base acompanhará todas as instâncias de suas classes derivadas até que outra classe base seja declarada. Aqui está a aparência das minhas declarações de classe:
#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
};
Todos os tipos derivados herdarão publicamente dessa base, como:
class ChildA : public Parent {
public:
ChildA( const std::string& parentName, std::string& myName, ChildType type );
};
A idéia que tenho em mente para usar essa hierarquia de classes em meu principal seria a seguinte
#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;
}
Eu sei como criar um ponteiro estático com uma função estática para obter esse ponteiro da classe para ter apenas uma instância durante o tempo de execução do aplicativo. Eu só quero saber se existe algum modo de usar um shared_ptr ou um unique_ptr e, depois de criar com êxito pelo menos uma instância de um tipo base, primeiro salvando o ponteiro (this) em qualquer tipo de ponteiro inteligente? Eu estava preferindo fazer um único, onde a classe pai "possui" seu próprio ponteiro.
Se você precisar de mais informações, entre em contato e atualizarei esta pergunta conforme solicitado, como mostrar a definição do construtor da minha classe base.