标签: unique-ptr

为什么我可以复制unique_ptr?

可能重复:
从函数返回unique_ptr

20.7.1.2 [unique.ptr.single]定义了这样的复制构造函数:

// disable copy from lvalue
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
Run Code Online (Sandbox Code Playgroud)

那么,为什么下面的代码编译得很好?

#include <memory>
#include <iostream>

std::unique_ptr< int > bar()
{
  std::unique_ptr< int > p( new int(4));
  return p;
}

int main()
{
  auto p = bar();

  std::cout<<*p<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我编译它像这样:

g++ -O3  -Wall -Wextra -pedantic -std=c++0x kel.cpp
Run Code Online (Sandbox Code Playgroud)

编译器:g ++版本4.6.1 20110908(Red Hat 4.6.1-9)

c++ g++ unique-ptr c++11

23
推荐指数
2
解决办法
2万
查看次数

析构函数和unique_ptr

我有以下代码

class A {
    public:
        A(){}
        ~A(){}
    private:
        std::vector<std::unique_ptr<double> > x;
};

A f() {
    A a;
    return a;
}

int main() {
    A a=f();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

除非我注释掉析构函数,否则它不会编译(gcc 4.7).实际上,我在代码中并不需要这个析构函数,我只是想将它用于调试目的.

但是,我不明白发生了什么,因此我担心我做错了什么.这里发生了什么?

c++ unique-ptr c++11

23
推荐指数
1
解决办法
4794
查看次数

Boost.Python:如何公开std :: unique_ptr

我对boost.python相当新,并尝试将函数的返回值公开给python.

函数签名如下所示:

 std::unique_ptr<Message> someFunc(const std::string &str) const;
Run Code Online (Sandbox Code Playgroud)

在python中调用函数时,我收到以下错误:

TypeError: No to_python (by-value) converter found for C++ type: std::unique_ptr<Message, std::default_delete<Message> >
Run Code Online (Sandbox Code Playgroud)

我在python中的函数调用如下所示:

a = mymodule.MyClass()
a.someFunc("some string here") # error here
Run Code Online (Sandbox Code Playgroud)

我试图暴露std :: unique_ptr但只是无法让它工作..有人知道如何正确暴露指针类?谢谢!

编辑: 我尝试了以下内容:

class_<std::unique_ptr<Message, std::default_delete<Message>>, bost::noncopyable ("Message", init<>())

;
Run Code Online (Sandbox Code Playgroud)

这个例子编译,但我仍然得到上面提到的错误.此外,我试图暴露类Message本身

class_<Message>("Message", init<unsigned>())

        .def(init<unsigned, unsigned>()) 
        .def("f", &Message::f)
;
Run Code Online (Sandbox Code Playgroud)

c++ python unique-ptr boost-python c++11

23
推荐指数
1
解决办法
3128
查看次数

C++ std :: unique_ptr从函数返回并测试为null

我有一个函数需要返回一个指向类对象的指针myClass.为此我正在使用std::unique_ptr.

如果函数成功,它将返回一个指向带有数据的对象的指针.如果失败,它应该返回null.

这是我的代码skelepton:

std::unique_ptr<myClass> getData()
{
   if (dataExists)
      ... create a new myClass object, populate and return it ...

   // No data found
   return std::unique_ptr<myClass> (null); <--- Possible ?
}
Run Code Online (Sandbox Code Playgroud)

main:

main()
{
   std::unique_ptr<myClass> returnedData;

   returnedData = getData();

   if (returnedData != null)   <-- How to test for null ?
   {
      cout << "No data returned." << endl;
      return 0;
   }

   // Process data
}
Run Code Online (Sandbox Code Playgroud)

所以这里是我的问题:

a)是否null可以使用std::unique_ptr?(返回一个对象或)?

b)如果可能,如何实施?

c)如果不可能,有哪些替代方案? …

c++ unique-ptr c++11

23
推荐指数
3
解决办法
5万
查看次数

了解复制初始化和隐式转换

我无法理解为什么以下复制初始化无法编译:

#include <memory>

struct base{};
struct derived : base{};

struct test
{
    test(std::unique_ptr<base>){}
};

int main()
{
    auto pd = std::make_unique<derived>();
    //test t(std::move(pd)); // this works;
    test t = std::move(pd); // this doesn't
}
Run Code Online (Sandbox Code Playgroud)

A unique_ptr<derived>可以移入a unique_ptr<base>,那么为什么第二个语句有效但最后一个没有?执行复制初始化时是否不考虑非显式构造函数?

gcc-8.2.0的错误是:

conversion from 'std::remove_reference<std::unique_ptr<derived, std::default_delete<derived> >&>::type' 
{aka 'std::unique_ptr<derived, std::default_delete<derived> >'} to non-scalar type 'test' requested
Run Code Online (Sandbox Code Playgroud)

从clang-7.0.0开始

candidate constructor not viable: no known conversion from 'unique_ptr<derived, default_delete<derived>>' 
to 'unique_ptr<base, default_delete<base>>' for 1st argument
Run Code Online (Sandbox Code Playgroud)

现场代码可在此处获得.

c++ unique-ptr implicit-conversion c++17

23
推荐指数
2
解决办法
970
查看次数

何时使用boost :: optional以及何时使用std :: unique_ptr,如果你想实现一个可以返回"nothing"的函数?

根据我的理解,有两种方法可以实现有时不返回结果的函数(例如,在ppl列表中找到的人).

* - 我们忽略原始ptr版本,与bool标志配对,以及未找到版本时的异常.

boost::optional<Person> findPersonInList();
Run Code Online (Sandbox Code Playgroud)

要么

std::unique_ptr<Person> findPersonInList();
Run Code Online (Sandbox Code Playgroud)

那么有什么理由可以优先于另一个吗?

c++ boost unique-ptr c++11 boost-optional

22
推荐指数
5
解决办法
8067
查看次数

unique_ptr的static_pointer_cast替代方案

我知道使用static_pointer_castwith unique_ptr会导致所包含数据的共享所有权.
换句话说,我想做的是:

unique_ptr<Base> foo = fooFactory();
// do something for a while
unique_ptr<Derived> bar = static_unique_pointer_cast<Derived>(foo);
Run Code Online (Sandbox Code Playgroud)

无论如何,这样做的结果是两个unique_ptr不应该同时存在,所以它只是被禁止.
是的,绝对有道理,这就是为什么不存在static_unique_pointer_cast确实存在的原因.

到目前为止,在我想存储指向这些基类的指针的情况下,但我还需要将它们转换为某些派生类(例如,想象一下涉及类型擦除的场景),我使用了shared_ptrs因为我的'如上所述.

无论如何,我猜测是否有替代方案可以shared_ptr解决这样的问题,或者在这种情况下它们是否真的是最佳解决方案.

c++ casting shared-ptr unique-ptr c++11

22
推荐指数
2
解决办法
2万
查看次数

Valgrind在std :: make_unique中显示内存泄漏

我正在使用Valgrind来检查内存泄漏.不幸的是我收到了Leak_DefinitelyLost警告.

附件是我的代码的简化版本,它重现了错误:

#include <iostream>
#include <vector>
#include <memory>
#include <unordered_map>

using namespace std;

class Base{
public:
    explicit Base(double a){
        a_ = a;
    }
    virtual void fun() = 0;

    protected:
        double a_;
};


class Derived_A : public Base{

    public:
        Derived_A(double a, vector<double> b, vector<double> c): Base(a), b_{b}, c_{c}{
        }
        void fun() override{
            cout << "Derived_A " << a_ << endl;
        }

    private:
        vector<double> b_;
        vector<double> c_;
};


class Derived_B : public Base{

    public:
        Derived_B(double a, double b, double c): …
Run Code Online (Sandbox Code Playgroud)

c++ memory-leaks undefined-behavior unique-ptr virtual-destructor

22
推荐指数
1
解决办法
1898
查看次数

unique_ptr&vector,尝试访问已删除的函数,Visual Studio 2013

我正在尝试使用unique_ptr来管理我的记忆,而VS2013似乎在给我带来麻烦,我认为它不应该.

似乎编译器无论出于什么原因试图访问已删除的拷贝构造函数,而它真的应该没有理由这样做.

这是我的一个类看起来像:

class Mesh
{
public:
    Mesh(oglplus::Program* program, const std::vector<Vertex>& vertices, 
                    const std::vector<GLuint>& indices);
    void draw();
private:
    const oglplus::Program* _program;
    std::vector<Vertex> _vertices;
    std::vector<GLuint> _indices;
    oglplus::Buffer _faceBuffer;
    oglplus::Buffer _vertexBuffer;
    oglplus::VertexArray _vao;
};

class Model
{
public:
    Model(std::string filename, oglplus::Program* program);
    void draw();
private:
    const oglplus::Program* _program;
    std::vector<std::unique_ptr<Mesh>> _meshes;
};
Run Code Online (Sandbox Code Playgroud)

问题出在线上

 std::vector<std::unique_ptr<Mesh>> _meshes;
Run Code Online (Sandbox Code Playgroud)

它开始喷出像这样的东西

2>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(593): error C2280: 'std::unique_ptr<Model::Mesh,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
2>          with
2>          [
2>              _Ty=Model::Mesh
2>          ]
2> …
Run Code Online (Sandbox Code Playgroud)

c++ unique-ptr visual-c++ visual-studio-2013 oglplus

21
推荐指数
1
解决办法
2万
查看次数

如何使用unique_ptr执行dynamic_cast?

我有一个类层次结构如下:

class BaseSession : public boost::enable_shared_from_this<BaseSession>
class DerivedSessionA : public BaseSession
class DerivedSessionB : public BaseSession
Run Code Online (Sandbox Code Playgroud)

在派生类函数中,我经常调用这样的函数:

Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this()));
Run Code Online (Sandbox Code Playgroud)

由于我正在与shared_ptr管理会议,这工作正常.最近,我发现我shared_ptr对这种情况的使用不是最佳的.这是因为这些会话是单个对象,每个客户端维护一个套接字.如果重新连接套接字,则会话副本将成为僵尸.

作为解决方法,我开始通过shared_ptr引用传递而不是复制.这解决了僵尸问题.

理想情况下,我觉得我应该unique_ptr用来存储会话,然后将引用传递给其他函数.这打开了一大堆蠕虫.

如何将基类unique_ptr对象转换为派生类unique_ptr对象?unique_ptr以下行的版本是什么?

Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this()));
Run Code Online (Sandbox Code Playgroud)

我只想要一个会话对象的副本,其他一切都应该是参考.

c++ boost dynamic-cast smart-pointers unique-ptr

21
推荐指数
2
解决办法
2万
查看次数