如何防止复制蝇量级对象
How can I prevent copying of flyweight objects?
我正在使用key_value flyweights学习,并编写了以下代码:
#include <iostream>
#include <string>
#include <boost/flyweight.hpp>
#include <boost/flyweight/key_value.hpp>
#include <boost/flyweight/no_locking.hpp>
class Foo
{
std::string name_;
public:
Foo(const std::string& name) { name_ = name; std::cout << "created " << name << "n"; }
Foo(const Foo& f) { name_ = f.name_; std::cout << "Copiedn"; }
~Foo() {std::cout << "Destroyed " << name_ << "n"; }
};
typedef boost::flyweight< boost::flyweights::key_value<std::string, Foo >, boost::flyweights::no_locking > FooLoader;
int main()
{
{
Foo myF = FooLoader("bar");
}
}
当我运行它时,我得到了以下输出:
created bar
Copied
Destroyed bar
Destroyed bar
我想避免额外的复印件,因为我真正的Foo复印起来很贵。这也是我使用蝇量级的主要原因。那么,有没有办法避免额外的副本?
您不必担心,因为编译器可能会在某些情况下使用RVO对此进行优化。尽可能使用编译器选项启用此类优化。
尤其是对于C++11,您几乎不应该担心它,因为它引入了移动语义,即使在轻量级模式中动态创建了一些临时对象,也不会花费太多成本。
相关文章:
- 防止临时对象文件访问 MSVC 中的磁盘
- 防止在按值传递对象(继承)时进行切片
- 如何防止类中的类对象尝试在没有默认构造函数的情况下自动构造自身?
- 防止通过接口删除对象
- 创建对象并防止被破坏
- 如何防止构造函数在引发异常时创建对象
- c++ 防止类共享静态对象
- 防止const函数被调用非const对象
- 防止 std::在对象上移动
- 防止删除对象上的函数调用
- 防止在执行时将两个类中的两个对象转换为 bool:if(a!=b)
- 成员初始值设定项列表的使用如何防止在c++中创建冗余对象
- 对象文件"Version References"从何而来?
- 如何防止类对象的构造?
- 我可以防止对象被 std::memcpy 复制吗?
- 我可以防止 std::sort 复制传递的比较对象吗?
- 将指针分配给临时对象--如何防止它
- 防止将对象强制转换为除一种类型C++之外的任何类型
- 如何防止线程使用的对象被丢弃?如何控制对象的生存期
- 对象具有防止匹配的类型限定符(未找到函数重载)