通过解引用复制std :: unique_ptr的值 [英] Copying std::unique_ptr's value via dereferencing

查看:105
本文介绍了通过解引用复制std :: unique_ptr的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码,尝试将 unique_ptr 对象的值复制到结构中.

I wrote the following code where I try to copy the value of unique_ptr object into a structure.

#include <iostream>
#include <memory>
using namespace std;

struct S {
    S(int X = 0, int Y = 0):x(X), y(Y){}

    // S(const S&) {}
    // S& operator=(const S&) { return *this; }

    int x;
    int y;
    std::unique_ptr<S> ptr;
};

int main() {
    S s;
    s.ptr = std::unique_ptr<S>(new S(1, 4));
    S p = *s.ptr; // Copy the pointer's value
    return 0;
}

它在Visual C ++ 2012中弹出错误:

It pops up errors in Visual C++ 2012:

IntelliSense:没有合适的用户定义的从"S"到"S"的转换存在
IntelliSense:没有运算符"="匹配这些操作数操作数类型为:std :: unique_ptr> = std :: unique_ptr>
错误C2248:'std :: unique_ptr< _Ty> :: unique_ptr':无法访问在类'std :: unique_ptr< _Ty>'

IntelliSense: no suitable user-defined conversion from "S" to "S" exists
IntelliSense: no operator "=" matches these operands operand types are: std::unique_ptr> = std::unique_ptr>
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

除非我取消对尝试定义复制构造函数和= operator的行的注释.这样可以消除编译器错误,但不能消除IntelliSense错误.不管错误列表中显示的IntelliSense错误如何,它都可以编译.

Unless I uncomment the lines where I attempted to define a copy constructor and =operator. This gets rid of the compiler errors but not the IntelliSense errors. It compiles regardless of IntelliSense errors showing in error list.

那么,为什么它不能仅使用默认函数并对其进行编译?我是否以正确的方式复制了价值?如果需要,应该如何定义复制构造函数?

So, why cannot it just use the default functions and compile with them? Am I doing the copy of value the right way? How should I define the copy constructor if it needs one?

推荐答案

由于您具有用户定义的构造函数,因此不会隐式生成副本构造函数,为什么您尝试复制 S 的尝试失败了.

The copy constructor is no implicitly generate because you have a user defined constructor, why is why your attempt to copy an S fails.

但是, unique_ptr 是不可复制的,只能是 movable ,因此您可以对 S move构造函数>:

But still, unique_ptr are not copyable, only movable, so you can use a move constructor for S :

S(S&& other) : x(other.x), y(other.y), ptr(std::move(other.ptr))
{

}

并命名为:

S p = std::move(s); // Move s to p


实时演示

这篇关于通过解引用复制std :: unique_ptr的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆