Reputation: 397
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?
Upvotes: 0
Views: 922
Reputation: 31468
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.
Upvotes: 1
Reputation: 38161
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:
VBO& VAO::GetVBO() const
{
return *m_VBO;
}
std::unique_ptr<VBO> VAO::takeVBO()
{
return std::move(m_VBO);
}
VBO
:std::unique_ptr<VBO> VAO::clone() const
{
return std::make_unique<VBO>(*m_VBO);
}
std::unique_ptr
to std::shared_ptr
Upvotes: 5
Reputation: 39
Your get function should look like
std::unique_ptr<VBO>& VBO::GetVBO()
{
return m_VBO;
}
Upvotes: -2