简体   繁体   中英

How do I use a “get” method to return a private std::unique_ptr member of a class

I have created a class with private, std::unique_ptr members, viz., m_VBO and m_EBO , as shown.

class VAO {

public:
    VAO();
    std::unique_ptr<VBO> GetVBO();
    std::unique_ptr<EBO> GetEBO();

private:
    std::unique_ptr<VBO> m_VBO;
    std::unique_ptr<EBO> m_EBO;
};

The class also includes "get" methods to protect and return those members for use when needed.

The definition of those "get" methods is,

//*************************************************************************************************
std::unique_ptr<VBO> VAO::GetVBO()
{
    return std::make_unique<VBO>(m_VBO);
    //return std::make_unique<VBO>();
}

//*************************************************************************************************
std::unique_ptr<EBO> VAO::GetEBO()
{
    //return std::make_unique<EBO>(m_EBO);
    return std::make_unique<EBO>();
}

which is not working.

I cannot figure out the correct technique for writing the "get" methods.

How is it done?

Unique pointer as name says is unique. So you can't clone it! You can only move it.

So basically depending on your needs there are couple reasonable solutions:

  1. Expose reference to object (or raw pointer to object):
VBO& VAO::GetVBO() const
{
    return *m_VBO;
}
  1. Transfer of ownership:
std::unique_ptr<VBO> VAO::takeVBO()
{
    return std::move(m_VBO);
}
  1. Provide clone functionality for VBO :
std::unique_ptr<VBO> VAO::clone() const
{
    return std::make_unique<VBO>(*m_VBO);
}
  1. Change std::unique_ptr to std::shared_ptr


I recommend watching: Herb Sutter “Leak-Freedom in C++... By Default.”

If you are sharing pointers with others you need to consider who is in charge of life time of the object pointed to.

If there can only ever be a single entity in charge of lifetime, then std::unique_ptr is a good choice. You then have the options of either passing lifetime management responsibilities to someone else, by moving the unique_ptr. Or you can give out raw pointers if you know that your clients are only observers and will not participate in lifetime management (and you then need to ensure that the entity holding the unique_ptr outlives all observers).

If multiple entities should all be able to individually keep an object alive - shared ownership - then a std::shared_ptr is a better choice.

Your get function should look like

std::unique_ptr<VBO>& VBO::GetVBO()
{
    return m_VBO;
}

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