我编写了以下代码,尝试将unique_ptr
对象的值复制到结构中。
#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 中弹出错误:
IntelliSense:不存在从“S”到“S”的合适的用户定义转换
IntelliSense:没有运算符“=”匹配这些操作数操作数类型是:std::unique_ptr> = std::unique_ptr>
error C2248: 'std::unique_ptr <_Ty>::unique_ptr' : 无法访问在类 'std::unique_ptr<_Ty>' 中声明的私有成员
除非我取消注释我试图定义复制构造函数和 =operator 的行。这消除了编译器错误,但没有消除 IntelliSense 错误。无论错误列表中显示的 IntelliSense 错误如何,它都会编译。
那么,为什么它不能只使用默认函数并使用它们进行编译呢?我是否以正确的方式复制价值?如果需要,我应该如何定义复制构造函数?