将临时作为引用传递
Passing a temporary as a reference
本文关键字:引用 更新时间:2023-10-16
我目前正试图通过这篇文章来理解复制和交换习惯用法。张贴的答案中有以下代码
class dumb_array
{
public:
// ...
friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}
// move constructor
dumb_array(dumb_array&& other)
: dumb_array() // initialize via default constructor, C++11 only
{
swap(*this, other); //<------Question about this statement
}
// ...
};
我注意到作者使用了这个语句
swap(*this, other);
CCD_ 1是作为对方法交换的引用而传递的临时或CCD_。我不确定我们是否可以通过引用传递右值。为了测试这一点,我尝试了这样做,但以下操作不起作用,直到我将参数转换为const reference
void myfunct(std::string& f)
{
std::cout << "Hello";
}
int main()
{
myfunct(std::string("dsdsd"));
}
我的问题是,other
作为一个临时的swap(*this, other);
如何通过引用传递,而myfunct(std::string("dsdsd"));
不能通过引用传递。
构造函数采用右值引用,但other
是一个左值(它有一个名称)。
在的情况下
myfunct(std::string("dsdsd"));
值std::string("dsdsd")
是对myfunct()
的调用实际上不在其范围内的临时值。
C++明确指定将引用绑定到const将临时的生存期扩展到引用本身的生存期。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?