-1

我有课:

class A{
public:
    A(int v){
        this->v=new int;
        *(this->v)=v;
    }
    ~A(){
        delete v;
    }
    A add(A &a, A  &b){
        A res(0);
        *(res.v)=*(a.v)+*(b.v)+*v;
        return res;
    }
    int get(){
        return *v;
    }
private:    
    A();
    int* v;    
    void operator=(const A &other);
    TreePointer(const A &other);
};

我想按如下方式使用它:

A finalRes=a.add(b,c).add(a,a);

它工作得很好,没有任何内存泄漏。但是如何在不使用 NRVO 优化的情况下实现类似的行为和用法呢?为此目的存在哪些标准设计模式?

4

1 回答 1

0

避免newstd::unique_ptr而是更喜欢。

实际上,就您而言,您甚至不需要指针:

class A{
public:
    explicit A(int v) : v(v){}
    ~A() = default;
    void operator=(const A &) = default;
    A(const A &) = default;
    A add(const A& a, const A& b) const { return A{v + a.v + b.v}; }
    int get() const { return v; }
private:
    int v;
};
于 2016-08-13T23:21:55.797 回答