What type of pointer should I return from the static element method

I come mainly from the Java world, but I recently wrote a bunch of C ++ and still do not really understand how to use pointers or what types of pointers to use there. I will give a brief example of my case and keep in mind the question that I really ask: "What type of pointer should I use and why?".

The perfect parallel with my code is to consider a class for a chain link. Each link has a parent link, with the exception of the root link which can be only 1.

// Link.hpp
class Link
{
public:
    Link(const std::string &linkName, Link *parentLink);
    Link(const std::string &linkNam);
    static Link* createRootLink(const std::string &linkName);
    static Link* getRootLink();

private:
    static Link *rootLink;
    Link *parentLink;
}

//Link.cpp
Link* Link::rootLink = Link::createRootLink("root");

Link* Link::createRootLink(const std::string &linkName);
{
    // Is raw pointer correct here or should I 
    // use a different pointer type, i.e. smart_pointer, 
    // shared_pointer, etc?
    Link *rootLink = new Link(linkName); 
    return rootLink;
}

Link* getRootLink()
{
     return rootLink;
}

Link::Link(const std::string &linkName)
{
    this->linkName = linkName;
    this->parentLink = NULL; // Root link has no parent link.
}

Link::Link(const std::string &linkName, Link *parentLink)
{
    this->linkName = linkName;
    this->parentLink = parentLink;
}

Hope this is clear enough. I Java this type of thing is simple, but in C ++ I'm not sure how to control the need for pointers to static objects. Thank you in advance for your cooperation!

+4
4

( ):

class Link
{
public:
    Link(const std::string &linkName, Link *parentLink);
    Link(const std::string &linkNam);
    static Link* getRootLink() {
        static std::unique_ptr<Link> root(new Link("root"));
        return root.get();
    }
};

, getRootLink ( , .)

, unique_ptr , . , , .

+2

A Link* , , (static) - Link.

+2

std::unique_pointer<Link> std::shared_pointer<Link> ( ++ 11) std::auto_ptr<Link>.

, ( , ) . Java - Java - , .

+1

, . , createRootLink() getRootLink(), .

class Link
{
public:
    Link(const std::string& name, Link& parent) : name(name), parent(&parent) {}
    Link(const std::string& name) : name(name), parent(nullptr) {}

    static Link createRootLink(const std::string& name)
    {
        return Link(name);
    }

    static Link& getRootLink() 
    {
         static Link rootLink = createRootLink("root");
         return rootLink;
    }

private:
    std::string name;
    Link *parent;
};
+1

All Articles