考虑我有一个容器std::map<int, std::shared_ptr<MyClass>>
,我想将它填充到外部函数中并避免处理它的内容。所以我有
typedef Container std::map<int, std::shared_ptr<MyClass>>
Container&& f(){
Container bar;
auto foo = std::shared_ptr<MyClass>(new MyClass());
bar.insert(std::make_pair(0,foo));
std::cout<<bar.at(1)->print_smth<<'\n'; //This works
return std::move(bar);
}
int main(){
Container baz(f());
std::cout<<bar.at(1)->print_smth<<'\n'; //This doesn't
// Container baz has element 1, but shared_ptr is invalidated, because it has 0 references.
}
如果我使用传统的复制构造函数,一切都会按预期工作。