【发布时间】:2023-03-23 14:48:01
【问题描述】:
我编写了以下代码,尝试将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>
错误 C2248:“std::unique_ptr<_ty>::unique_ptr”:无法访问 在类'std::unique_ptr<_ty>'中声明的私有成员
除非我取消注释我试图定义复制构造函数和 =operator 的行。 这消除了编译器错误,但没有消除 IntelliSense 错误。无论错误列表中显示的 IntelliSense 错误如何,它都会编译。
那么,为什么不能只使用默认函数并使用它们进行编译呢?我是否以正确的方式复制价值?如果需要,我应该如何定义复制构造函数?
【问题讨论】:
标签: c++ c++11 unique-ptr visual-c++-2012