c++ - 如何将指针的右值转换为左值?

标签 c++ c++11

class Attr
{
public:
   Attr();
   Attr(const std::wstring& name)
   {
      ...
   }
};

class AttrDec : public Attr
{
public:
   AttrDec(Attr* attr)
      :Attr()
   {
      _attr = attr;
   }
   AttrDec(Attr*&& attr)
      :Attr()
   {
      _attr = std::move(attr);
   }

private:
   Attr* _attr;
};

class XAttr : public AttrDec
{
public:
   XAttr(const std::wstring& name)
      :AttrDec(&Attr(name)) //HERE!!!
   {}
}

在标记的位置我收到警告:

nonstandard extension used: class rvalue used as lvalue.

但是我在 AttrDec 类中定义了移动构造函数!

我该如何解决这个警告?

最佳答案

解决这个问题的正确方法是按值存储,然后让 move 执行它的操作。移动指针不会移动仍将消失的底层临时值,并且您将有一个移动的悬空指针指向任何地方:

class Attr
{
public:
   Attr();
   /*explicit depending on needs*/ Attr(const std::wstring& name)
   {
      ...
   }
}

class AttrDec : public Attr
{
public:
   AttrDec(Attr attr)
      :Attr()
      , attr_(attr)
   {
   }
   AttrDec(Attr&& attr)
      :Attr()
      , attr_(std::move(attr))
   {
   }

private:
   Attr attr_;
}

class XAttr : public AttrDec
{
public:
   XAttr(const std::wstring& name)
      : AttrDec(Attr(name)) //HERE!!!
   {}
}

关于c++ - 如何将指针的右值转换为左值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33785800/

相关文章:

c++ - 为什么 std::unique_lock 使用类型标签来区分构造函数?

c++ - 用 C++ 编写的高质量开源文本转语音 (TTS) 引擎

c++ - 交替错误: “Invalid dimension for argument 0”

c++ - 在抛出的异常中销毁临时字符串

c++ - ATL 库 :warning LNK4254 and LNK4078

c++ - 将指针传递给导致第二次调用使程序崩溃的函数

c++ - 如何在开放源IDE(codelite)中迁移到C++ 11

c++ - std::atomic bool 变量的访问顺序

c++ - 是否有任何 100% C++11 兼容的 std 实现?

c++ - 如何在 Objective-C 中访问 Box2d 的 b2CollideCircles?