将初始值设定项列表与返回引用的用户定义转换运算符一起使用时,将复制返回值

Return value is copied when using initializer list with a user-defined conversion operator that returns reference

本文关键字:一起 运算符 定义 转换 返回值 复制 用户 返回 列表 引用      更新时间:2024-05-09

我正试图围绕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;
}

包装器类可以很好地进行赋值和圆括号初始化。

奇怪的是,当我试图用initializer list(上面代码中的#5和#6(初始化Nothing&时,值被复制了,我必须对它使用const引用。然而,当我显式调用像wrapper.operator Nothing &()(上面代码的#2(这样的转换运算符时,我得到了对第一行构造的原始对象的正确引用。

我读过cppreference,发现initializer列表是一个复制初始化的临时列表,但它不理解为什么当显式调用operator Nothing &()时代码会工作。

有人能帮我弄清楚这里发生了什么吗?非常感谢!

您实际上是在这里进行引用初始化:

Nothing & by_initialization_2{wrapper};

规则规定,由于初始值设定项与绑定的引用的类型不同,因此会考虑用户定义的转换运算符,这很好,因为您有合适的转换运算符。

但是,如果转换函数返回的l值是通过一个大括号init列表传递的,那么一个临时值就会具体化。由于无法将非常数引用绑定到临时引用,因此初始化失败。