如何将右值生存期扩展到自定义容器生存期
How do I extend rvalue lifetime to my custom container lifetime?
让我有一个自定义包装容器。我想这样使用它:
double d = 3.14;
MyContainer<std::vector<int>> pointer = new std::vector<int>();
MyContainer<std::string> rvalue = std::string("foo");
MyContainer<int> rvalue2 = 5 + 8;
MyContainer<double> lvalue = d;
我不想存储右值的副本(引用是可以的)。Rvalue引用允许我这样做:
std::string string1 = "foo";
std::string string2 = "bar";
std::string&& string3 = string1 + string2;
string3 += "test";
基本上,我想将rvalues的生存期延长到容器的生存期。然而,当我这样做时:
template<class T>
class MyContainer {
public:
MyContainer(T&& obj) : object(obj) {}
T&& object
...
};
...
MyContaier<std::string> container = MyContainer(std::string("foo"));
我收到一个错误(无法将"std::string"左值绑定到"std:;:string&")。这个例子略有不同,但我只是想了解一个大致的想法。我该如何避免这种情况?
除了您的代码有多个拼写错误和语法错误外,在技术上没有任何东西可以阻止您获取std::string
的右值引用(尽管您的赋值/构造函数调用不正确)。保持T&;作为成员变量,它不会像您想象的那样工作。一旦到达下一个序列点,存储对过期右值的引用,然后访问它将是UB。
下面是一个使用右值引用和左值引用构造函数的工作示例。如果你想"拥有"对象,你需要在对象内部有一个实际的实例。从技术上讲,你不能延长即将过期的rvalue的生存期;你只能建造其他可以重复使用它的东西(希望能偷走它一些昂贵的内脏)。希望这能有所帮助。
#include <utility>
#include <string>
#include <iostream>
template<class T>
class MyContainer {
public:
// makes a copy from an lvalue reference
MyContainer(const T& obj)
: object(obj) {
}
// moves from an rvalue reference
MyContainer(T&& obj)
: object(std::move(obj)) {
}
MyContainer& operator=(const T& obj) {
object = obj;
}
MyContainer& operator=(T&& obj) {
object = std::move(obj);
}
T object;
};
int main() {
MyContainer<std::string> container = std::string("foo");
std::cout << container.object;
}
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- GCC对可能有效的代码抛出init list生存期警告
- 在不复制临时对象的情况下延长其生存期
- 结束另一个线程中使用的对象的生存期
- C++17 和静态临时生存期的参考扩展
- 从“if constexpr”分支扩展对象生存期/范围
- 为什么免费存储区中对象的生存期绑定到范围
- 临时绑定到引用参数的默认参数的生存期是多少
- 如何将右值生存期扩展到自定义容器生存期
- 使函数内联是否会影响绑定到其参数的临时变量的生存期
- 将循环中的元素添加到容器(生存期)
- “make_shared”如何避免双重分配并允许“释放”将托管对象的生存期延长到超出shared_pointer的生存期
- 绑定到函数参数的引用是否会延长该临时参数的生存期
- 如何将共享资源对象的生存期绑定到其用户生存期的联合中?
- 从C扩展跟踪CPython对象的生存期
- 当 xvalue 绑定到常量左值引用时,它的生存期是否会延长?
- 未扩展常量引用变量的生存期
- 什么决定临时变量的生存期何时扩展为常量引用或重值引用
- 为什么临时的生存期不会延长到封闭对象的生存期?
- 生存期扩展和条件运算符