指针或局部变量,用于函数的输出参数



如果我想在映射中使用元素的值作为函数的输出参数,那将其声明为智能指针还是本地?

例如:

// .h
class A {
   private:
    // Is the below code preferred over 
    // std::map<int, std::unique_ptr<B>>?
    std::map<int, B> map;
   public:
    void Func1();
    // Message is the output parameter
    void Func2(int, B* message);
} 
// .cc
void A:: Func1() {
   B b;
   // Is it better to make b a smart pointer and use std::move 
   // to transfer the ownership to map?
   map.insert(std::make_pair(1, b));
   for (const auto& x : map) {
     Func2(x->first, &x->second);
   }
}

在上面的示例中,最好声明B的智能指针,然后将指针传递给FUNC2?

谢谢,

std::map制作了您放入的内容 1 ,因此map拥有提供给func2b的副本。这里不需要智能指针,因为map将处理所有存储的B s的破坏。

实际上根本不需要指针。func2可以是void Func2(int, B & message);并使用参考。

1 您可以将指针存储在std::map中,并且std::map将包含 Pointer 的副本。指向的数据未复制,需要外部管理来处理破坏。这是使用智能指针的一个很好的案例,但是在容器中存放指针首先击败了使用容器的许多好处,并且最好避免使用。

最新更新