相关疑难解决方法(0)

从函数返回unique_ptr

unique_ptr<T>不允许复制构造,而是支持移动语义.然而,我可以unique_ptr<T>从函数返回一个并将返回的值赋给变量.

#include <iostream>
#include <memory>

using namespace std;

unique_ptr<int> foo()
{
  unique_ptr<int> p( new int(10) );

  return p;                   // 1
  //return move( p );         // 2
}

int main()
{
  unique_ptr<int> p = foo();

  cout << *p << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码按预期编译和工作.那么该行如何1不调用复制构造函数并导致编译器错误呢?如果我必须使用line 2而不是它有意义(使用line 2也可以,但我们不需要这样做).

我知道C++ 0x允许此异常,unique_ptr因为返回值是一个临时对象,一旦函数退出就会被销毁,从而保证返回指针的唯一性.我很好奇这是如何实现的,它是在编译器中特殊的,还是在语言规范中有一些其他条款可以利用?

c++ unique-ptr c++11

328
推荐指数
6
解决办法
14万
查看次数

我们如何从成员函数返回unique_pointer成员?

我有一个带有指针成员的基类.我必须做出有根据的猜测,以确定它应该是a unique_ptr还是a shared_ptr.他们似乎都没有解决我的特定用例.

class Base
{
public:
    Base(): pInt(std::unique_ptr<int>(new int(10))) {};
    virtual std::unique_ptr<int> get() = 0;
    //Base(): pInt(std::shared_ptr<int>(new int(10))) {}; // Alternate implementation
    //virtual std::shared_ptr<int> get() = 0; // Alternate implementation
private:
    std::unique_ptr<int> pInt;
    //std::shared_ptr<int> pInt; // Alternate implementation
};
Run Code Online (Sandbox Code Playgroud)

基类已导出到Derived1Derived2.前者返回后者返回本地对象的unique_ptr成员.pIntunique_ptr

class Derived1: public Base
{
public:
    Derived1() {};
    virtual std::unique_ptr<int> get()
    {
        //return std::move(pInt);  Will compile but the ownership is lost
        return pInt;
    }
private:
    std::unique_ptr<int> pInt;
};
class …
Run Code Online (Sandbox Code Playgroud)

c++ pointers shared-ptr unique-ptr c++11

7
推荐指数
1
解决办法
1803
查看次数

标签 统计

c++ ×2

c++11 ×2

unique-ptr ×2

pointers ×1

shared-ptr ×1