指向容器的智能指针 [英] Smart pointer to container

查看:80
本文介绍了指向容器的智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然通过引用发送 stl 容器并不安全.用智能指针包装stl容器作为函数参数发送是否有意义?

While sending stl container by reference it's not as safe as may be. Does it make sense to wrap stl container by smart pointer to send as function argument?

template <typename T>
void f(const std::unique_ptr<T> up) {
  ...
}

std::unique_ptr<std::vector<char>> array;
f(std::move(array));

UPD:好的,让我们缩小问题的范围.我正在制作某个类的实例.我应该用容器构造它:

UPD: OK, let's narrow the question. I'm making an instance of some class. I should construct it with a container:

class MyClass {
  public: 
    MyClass(const std::vector<int>& ar) : m_ar(ar) {};
  private:
    std::vector<int> m_ar;
};

std::vector<int> tmp_ar;
tmp_ar.push_back(0);
tmp_ar.push_back(1);
tmp_ar.push_back(2);
MyClass mc(tmp_ar);

我不想在将容器发送到构造函数时复制容器,然后我使用对局部变量的引用.这段代码中的某些内容让我感到紧张.

I do not want to copy a container while sending it to the constructor, then I use reference to a local variable. Something in this code makes me nervous.

推荐答案

我不想在将容器发送到构造函数时复制容器,然后我使用对局部变量的引用.这段代码中的某些内容让我感到紧张.

I do not want to copy a container while sending it to the constructor, then I use reference to a local variable. Something in this code makes me nervous.

代码是正确的,因为 m_ar(ar) 正在制作 tmp_arcopy:mc 没有对局部变量 tmp_ar 的引用,因此 mctmp_ar 之间没有生命周期依赖.如果一个对象存储对另一个对象的引用并在另一个对象被破坏时尝试使用该引用,则可能会出现问题(参见 悬空指针,同样适用于引用.

The code is correct as a copy of tmp_ar is being made by m_ar(ar): mc has no reference to the local variable tmp_ar so there is no lifetime dependency between mc and tmp_ar. Problems can arise if an object stores a reference to another object and attempts to use that reference when the other object has been destructed (see dangling pointer, same applies to reference).

tmp_ar 可以是 std::move()d 改为在 tmp_ar 作为构造函数参数传递后不再需要时避免复制:

The tmp_ar could be std::move()d instead to avoid the copy if tmp_ar is no longer required after it has been passed as constructor argument:

class MyClass {
  public: 
    MyClass(std::vector<int> ar) : m_ar(std::move(ar)) {};
  private:
    std::vector<int> m_ar;
};

std::vector<int> tmp_ar {0, 1, 2};
// Use 'tmp_ar' ...
MyClass mc(std::move(tmp_ar));

这篇关于指向容器的智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆