Flyweight 객체의 복사를 어떻게 방지 할 수 있습니까?
-
09-12-2019 - |
문제
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 << "Copied\n"; }
~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");
}
}
.
실행할 때 나는 follwing 출력을 얻었습니다 :
created bar
Copied
Destroyed bar
Destroyed bar
.
나의 진짜 foo가 복사하는 것이 매우 비싸기 때문에 여분의 사본을 피하고 싶습니다.이것은 또한 Flyweight를 사용하는 주요 이유이기도합니다.그래서, 여분의 사본을 피하는 방법이 있습니까?
해결책
컴파일러가 RVO를 사용하여이를 최적화 할 수 있으므로 걱정할 필요가 없습니다.가능한 경우 모든 최적화를 활성화하려면 컴파일러 옵션을 사용하십시오.
및 특히 C ++ 11을 사용하면 파리 패턴에서 비행기에서 일부 임시 객체가 생성되는 경우에도 비용을 들이지 않는 이동 의미를 소개 했으므로 거의 걱정하지 않아야합니다.
제휴하지 않습니다 StackOverflow