我实际上想在类上使用 unique_ptr 做一个零规则的示例。 这是我的示例代码:
#include <iostream>
#include <memory>
// Rule of zero?
template <class T>
class myStruct
{
int m_timesToPrint{0};
std::unique_ptr<T> m_ptr;
public:
myStruct(int tToPrint, const T& val)
: m_timesToPrint(tToPrint), m_ptr(std::make_unique<T>(val))
{ }
myStruct() = default;
myStruct(const myStruct&) = default;
friend std::ostream& operator<<(std::ostream& os, const myStruct<T>& rhs)
{
for(auto i = 0; i < rhs.m_timesToPrint; ++i)
{
os << *(rhs.m_ptr.get()) << "\n";
}
os << "---------------\n";
return os;
}
};
int main()
{
myStruct<int> m1(3, 3);
// myStruct<int> m2 = m1; // Error!
std::cout << m1;
// std::cout << m2;
return 0;
}
显然,我在 m2 = m1 行上遇到问题,因为 unique_ptr(const unique_ptr&) =deleted
已被删除,但我该如何执行该示例?
谢谢!
最佳答案
使用零规则,甚至不需要默认构造函数:
template <class T>
class myStruct
{
int m_timesToPrint{0};
std::unique_ptr<T> m_ptr;
public:
myStruct(int tToPrint, const T& val)
: m_timesToPrint(tToPrint), m_ptr(std::make_unique<T>(val))
{ }
myStruct() = default;
// myStruct(const myStruct&) = default; // not needed
// ... other stuff
};
Obviously, i have a problem on
m2 = m1
line, becauseunique_ptr(const unique_ptr&) = deleted
is deleted, but how can i do that example?
嗯,你的零规则实现正确。如果您希望拷贝正常工作,您需要一个与 std::unique_ptr
不同的工具。
我的建议是创建一个复制其资源的指针类型,或者如果您想共享资源而不是复制它,则使用 std::shared_ptr
。
这样的指针可能如下所示:
template<typename T>
struct clone_ptr {
clone_ptr(clone_ptr const& other) : /* initialize `_ptr` with copy */ {}
clone_ptr(clone_ptr&&) = default;
clone_ptr& operator=(clone_ptr&&) = default;
// implement copy assign
// implement operators
private:
std::unique_ptr<T> _ptr;
};
关于c++ - 如何使用 unique_ptr 实现零规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59146954/