C++有移动和删除语义吗?
Does C++ have move and delete semantics?
是否可以在C++中创建一次性变量,而无需使用大括号进行任何时髦的业务?
以下是我想要实现的示例:
const float _phiTemp = atan2(tan(cluster.beta), tan(cluster.alpha));
const float phi = HALF_PI - std::abs(HALF_PI - std::abs(_phiTemp));
// After running this code I want _phiTemp to be unaccessible, and the
// compiler to send an error if I ever try
这是我想要的冗长而丑陋的实现:
const float phi = 0;
{
const float _phiTemp = atan2(tan(cluster.beta), tan(cluster.alpha));
float& phiRef = const_cast<float&> phi;
phiRef = HALF_PI - std::abs(HALF_PI - std::abs(std::move(_phiTemp)));
}
// _phiTemp is disposed and phi is a const, and safely used in the calculation
// through std::move()
我错过了什么吗?C++没有"即时"变量处置吗?
冗长而丑陋的实现也是未定义的行为;写入phiRef
是对定义为 const 的变量的写入。
你能做的最好的事情就是编写一个函数来计算phi
- 如果你想内联这样做,你可以写一个lambda:
const float phi = [&cluster]{
const float phiTemp = atan2(tan(cluster.beta), tan(cluster.alpha));
return HALF_PI - std::abs(HALF_PI - std::abs(phiTemp));
}();
。但它仍然很丑。我认为C++不提供此功能。
Martin Bonner 走在正确的轨道上:lambda 作为"范围与return
"效果很好,您可以在其中随意声明辅助变量。以下是我在个人工具包中所做的,以更进一步:
namespace initBlock_detail {
struct tag { };
template <class F>
decltype(auto) operator * (tag, F &&f) {
return std::forward<F>(f)();
}
}
#define glk_initBlock
glk::initBlock_detail::tag{} * [&]() -> decltype(auto)
调用语法如下所示:
const float phi = glk_initBlock {
const float phiTemp = atan2(tan(cluster.beta), tan(cluster.alpha));
return HALF_PI - std::abs(HALF_PI - std::abs(phiTemp));
};
我认为你想要的是一个临时变量。 即不要命名您的中间值。
const float phi = HALF_PI - std::abs(
HALF_PI - std::abs(
atan2(
tan(cluster.beta)
, tan(cluster.alpha)
)
)
);
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 何时在引用或唯一指针上使用移动语义
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 如何从具有移动语义的类对象中生成共享指针
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- C++有移动和删除语义吗?
- C++11 中已删除成员函数的确切语义是什么?
- 消除默认/删除移动/复制语义中涉及的样板的好方法是什么