使用初始化程序列表和返回引用的用户定义的转换运算符时,将复制返回值

问题描述

我正在尝试围绕shared_ptr编写一个包装程序,该包装程序可以隐式取消对基础类型的引用。代码如下:

#include <memory>

template<typename T>
class PtrWrapper {
public:
  PtrWrapper(std::shared_ptr<T> ptr) : ptr_(ptr) {}
  operator T& () {
    return *ptr_;
  }
  T& ref() {
    return *ptr_;
  }
private:
  std::shared_ptr<T> ptr_;
};

看起来没有任何问题。我尝试了几种使用包装器的方法:

#include <iostream>

class Nothing {
public:
  Nothing() {
    std::cout << "Construct " << this << std::endl;
  }
  Nothing(Nothing const& parent) {
    std::cout << "Copy " << &parent << " " << this << std::endl;
  }
  Nothing(Nothing && parent) {
    std::cout << "Move " << &parent << " " << this << std::endl;
  }
  ~Nothing() {
    std::cout << "Destruct " << this << std::endl;
  }
};

int main() {

  PtrWrapper<Nothing> wrapper{std::make_shared<Nothing>()};

  // #1: OK
  Nothing & by_assignment = wrapper;
  // #2: OK
  Nothing & by_operator{wrapper.operator Nothing &()};
  // #3: OK
  Nothing & by_function{wrapper.ref()};
  // #4: OK
  Nothing & by_initialization(wrapper);

  // #5: Compile error: non-const lvalue reference to type 'Nothing' cannot bind to an initializer list temporary
  // Nothing & by_initialization_2{wrapper};

  // #6: The `Nothing` class is copied,which is not expected
  Nothing const& by_initialization_3{wrapper};

  return 0;
}

包装器类可很好地与赋值和括号初始化一起使用。

奇怪的是,当我尝试使用初始化列表(上面代码中的#5和#6)初始化Nothing&时,将值复制并且必须使用const引用。但是,当我像wrapper.operator Nothing &()那样显式调用转换运算符时(上面的代码中为#2),我正确地引用了第一行中构造的原始对象。

我已经读过cppreference,发现初始化列表是一个复制初始化的临时列表,但是在显式调用operator Nothing &()时为什么代码可以工作并没有意义。

任何人都可以帮助我弄清楚这里发生了什么事?非常感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)