0

タイプ A のオブジェクトへのマップを生成する関数があります。

map<int,A> test()
{
    map<int, A> m;
    A a1(10); // constructor
    A a2(20);
    A a3(30);
    m[0] = a1; m[1] = a2; m[2] = a3; // <-- copy constructor and = operator
    return m;
}

この関数を実行すると、コンストラクターが呼び出され、コピー コンストラクターと = 演算子が呼び出されます。

map<int,A> x = test();

戻り値の最適化 (RVO) のように 1 つのコンストラクターのみを呼び出すようにコンパイラーを最適化する方法はありますか?

別のアプローチはポインターを使用することかもしれませんが、別の方法があるかどうか知りたいです。

map<int,A*> test3()
{
    map<int, A*> m;
    A* a1 = new A(10);
    A* a2 = new A(20);
    A* a3 = new A(30);
    m[0] = a1; m[1] = a2; m[2] = a3;
    return m;
}

...

map<int,A*> x = test3();

...

for (auto val: x)
{
    delete val.second;
}
4

2 に答える 2

0

スマートポインターでもテストしましたが、問題ないようです。

#include <iostream>
#include <map>
#include <memory>

using namespace std;

class A
{
    int x;
public: 
    A() {
        cout << "Default constructor called" << endl;
    }  
    A(const A& rhs) 
    {
        this->x = rhs.x;
        cout << "Copy constructor called" << endl;
    }
    A& operator=(const A& rhs)
    {
        this->x = rhs.x;
        cout << "Copy constructor called" << endl;
    }
    A(int x) : x(x) {
        cout << "*I'm in" << endl;
    }
    ~A() {
        cout << "*I'm out" << endl;
    }
    int get() const {return x;}
    void set(int x) {this->x = x;}
};

std::map<int,unique_ptr<A>> test()
{
    std::map<int, unique_ptr<A>> m;
    m[0] = unique_ptr<A>(new A(101));
    m[1] = unique_ptr<A>(new A(201));
    m[2] = unique_ptr<A>(new A(301));
    return m;
}

using namespace std;
int main(int argc, char *argv[]) {

    auto m = test();
    for (const auto& i: m)
    {
        cout << i.second->get() << endl;
    }    
}

結果:

*I'm in
*I'm in
*I'm in
101
201
301
*I'm out
*I'm out
*I'm out
于 2013-06-18T03:53:09.890 に答える