1

できる限りSSCEを作成しました。私の疑いは、メインでオブジェクトを要求する前に、共有ポインターがオブジェクトを分解 (解放) することです。共有ポインタを完全に回避せずにこれを防ぐにはどうすればよいですか? これは、shared_ptrs の使用によって大いに助けられるプログラムの孤立した問題です。

Test.h:

#ifndef TEST_H
#define TEST_H
#include <memory>
#include <iostream>
#include <vector>

class Test
{
    public:
        Test();
        virtual ~Test();
        static std::shared_ptr<Test> makeTestFrom(std::string l);
        std::vector<std::shared_ptr<int>> reg_vec;
    protected:
    private:

};

#endif // TEST_H

テスト.cpp

#include <memory>
#include <iostream>
#include <vector>
Test::Test():
reg_vec()
{
    //ctor
}

Test::~Test()
{
    //dtor
}
std::shared_ptr<Test> Test::makeTestFrom(std::string l)
{
    std::shared_ptr<Test> sp(new Test());
    std::shared_ptr<int> i(new int(3));
    sp->reg_vec.push_back(i);
    return sp;
}

main.cpp:

#include <memory>
#include <iostream>
#include <vector>
#include "include/Test.h"
using namespace std;

 int main()
{
    std::unique_ptr<Test> x(new Test());
    x->makeTestFrom("loldoesntmatter");
    std::cout << x->reg_vec[0] << std::endl;
    return 0;

}
4

2 に答える 2

4
 int main() {
    std::unique_ptr<Test> x(new Test());
    x->makeTestFrom("loldoesntmatter"); // you discarded the return
    std::cout << x->reg_vec[0] << std::endl; // x->reg_vec is empty
    return 0;

}

また、共有ポインタが多すぎます

于 2012-09-27T02:26:35.937 に答える
3

新しいオブジェクトが多すぎます。では、内側mainを探していますが、に何も追加しません。新しいオブジェクトを作成し、その中に整数を入れます。intx->reg_vecmakeTestFromx

それに加えて、あなたは虐待していますshared_ptr。C++ では、可能な場合は動的割り当てを避けてください。 intを使用するよりも値で渡す方が安価なshared_ptrので、そのまま使用してvector<int>ください。またTest、自動ライフタイムを使用してオブジェクトを作成することもできます。

他のいくつかの言語 (Java など) がすべてをハンドルにするからといって、それが C++ に適したパターンであるとは限りません。

于 2012-09-27T02:37:37.517 に答える