相关疑难解决方法(0)

如何将unique_ptr参数传递给构造函数或函数?

我是新手在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)

c++ arguments unique-ptr c++11

377
推荐指数
5
解决办法
15万
查看次数

临时 C++ 对象是左值吗?

我对以下代码感到困惑,它(对我来说令人惊讶)编译:

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)

有人可以进一步启发我了解这种行为吗?

c++

3
推荐指数
1
解决办法
308
查看次数

标签 统计

c++ ×2

arguments ×1

c++11 ×1

unique-ptr ×1