我是新手在C++ 11中移动语义,我不太清楚如何处理unique_ptr构造函数或函数中的参数.考虑这个引用自身的类:
#include <memory>
class Base
{
public:
typedef unique_ptr<Base> UPtr;
Base(){}
Base(Base::UPtr n):next(std::move(n)){}
virtual ~Base(){}
void setNext(Base::UPtr n)
{
next = std::move(n);
}
protected :
Base::UPtr next;
};
Run Code Online (Sandbox Code Playgroud)
这是我应该如何编写unique_ptr参数的函数?
我需要std::move在调用代码中使用吗?
Base::UPtr b1;
Base::UPtr b2(new Base());
b1->setNext(b2); //should I write b1->setNext(std::move(b2)); instead?
Run Code Online (Sandbox Code Playgroud) 我对以下代码感到困惑,它(对我来说令人惊讶)编译:
class A {
int a=0;
};
A returnsA(void)
{
static A myA;
return myA;
}
void works(void)
{
A anotherA;
returnsA() = anotherA;
}
Run Code Online (Sandbox Code Playgroud)
我在标准或网络上找不到任何表明它不应该编译的内容。对我来说,这似乎很奇怪。
我猜想returnsA()返回一个对象( 的副本myA),因此我们对其调用默认的复制赋值运算符,anotherA将其复制分配给返回的对象,然后该对象超出范围并被销毁。
我期待的行为更像这样,但无法编译:
int returnsint(void)
{
static int i=0;
return i;
}
void doesntwork(void)
{
int anotherint=0;
returnsint() = anotherint;
}
Run Code Online (Sandbox Code Playgroud)
有人可以进一步启发我了解这种行为吗?