防止通过引用传递右值
Prevent passing rvalue by reference
本文关键字:引用 更新时间:2023-10-16
在我的项目中,大多数对象都是在竞技场中创建的,并且可以保证它们在用户会话期间存在。因此,对于某些类来说,将 const 引用作为成员字段是非常安全的,例如:
class A {
public:
A(const string& str) : str_(str) {}
private:
const string& str_;
};
但这里有一个陷阱。如果错误地,可以通过以下方式创建A
实例:
A a("some temporal string object");
在该行中,时态string
对象已被隐式创建和销毁。因此,在此之后a
存储不正确的引用。
如何防止这种行为?如果它导致编译错误会更好...
你只需要有一个与右值更匹配的重载,以便编译器将那个重载放在const&
重载上。
因此,临时比const&
更匹配&&
,因此您只需要提供这样的构造函数并对其进行delete
:
class A {
public:
A(const string& str) : str_(str) {}
A(string&&) = delete; // this constructor is a better match for rvalues
private:
const string& str_;
};
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在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*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?