C++ 如何使用唯一的ptr实现零规则

C++ 如何使用唯一的ptr实现零规则,c++,pointers,unique,rules,zero,C++,Pointers,Unique,Rules,Zero,实际上,我想在一个类上用一个唯一的ptr做一个零规则的例子。 这是我的示例代码: #包括 #包括 //零法则? 模板 类myStruct { int m_timesToPrint{0}; std::唯一的\u ptr m\u ptr; 公众: myStruct(内部打印、常量和值) :m_timesToPrint(tToPrint),m_ptr(std::make_unique(val)) { } myStruct()=默认值; myStruct(constmystruct&)=默认值; fri

实际上,我想在一个类上用一个唯一的ptr做一个零规则的例子。 这是我的示例代码:

#包括
#包括
//零法则?
模板
类myStruct
{
int m_timesToPrint{0};
std::唯一的\u ptr m\u ptr;
公众:
myStruct(内部打印、常量和值)
:m_timesToPrint(tToPrint),m_ptr(std::make_unique(val))
{ }
myStruct()=默认值;
myStruct(constmystruct&)=默认值;

friend std::ostream&operator使用零规则,甚至不需要默认构造函数:

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
};

但是我该怎么做呢?这个例子你做不到。
unique\u ptr
是不可复制的。如果你希望你的类是可复制的,你需要为它定义逻辑。我应该使用什么样的智能指针?你的要求是冲突的。你不能同时满足这两个要求:要么放弃零要求规则,要么为它定义逻辑复制
std::unique_ptr
,或删除
std::unique_ptr
要求,并使用其他内容,而不是它。根据您的情况选择更有意义的内容。这取决于您想要的语义。您希望所有副本指向同一对象,还是希望所有副本都指向自己的对象,即副本?我想复制pointer value:)我想复制资源;)然后使用
myStruct(myStruct&&)=default;
@Eljay我看不出默认设置有什么帮助
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;
};