Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

memory - C++ : Alternative to constructor initializer lists without assignment?

I'm facing the following problem:

I want to pass the _partHandlePtr to the constructor of _currUnmanaged and _extUnmanaged but getting errors like "memory access violation occurred at address 0x00000010, while attempting to read inaccessible data". I also tried to initialize both instances after 2) but the problem is that I can't use the assignment operator on them. So is there another option to initialize _currUnmanaged and _extUnmanaged without using list initialization or is the problem elsewhere?

class DerivedCollect {

    DerivedCollect(
        const IGCollect& inputCollect,
        Handle handle) :
        _partHandlePtr(nullptr),
        _currUnmanaged(_partHandlePtr),
        _extUnmanaged(_partHandlePtr)
    {
        // 1) Filling _pHandles 

        _pHandles.push_back(HandleManager::GetPHandle(handle));

        for (const auto& it : inputCollect.GetPartHandles())
        {
            _pHandles.emplace_back(it);
        }

        // 2) Make _partHandlePtr referencing to _pHandles 

        _partHandlePtr = std::make_shared<std::vector<Handle>>(_pHandles);
    }

private:
    std::shared_ptr<std::vector<Handle>> _partHandlePtr;
    std::vector<Handle> _pHandles;
    UnmanagedCollect _currUnmanaged;
    UnmanagedCollect _extUnmanaged;
}
class UnmanagedCollect {
    UnmanagedCollect(
        std::shared_ptr<std::vector<Handle>> partHandlePtr) :
        _partHandlePtr(partHandlePtr)
    {
    }
private:
    std::shared_ptr<std::vector<Handle>> _partHandlePtr;
}

Thanks for suggestions and solutions!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suspect that what you're aiming for is to have one vector of "handles" that is shared (initially) with the two "unmanaged" members.

That would look something like this:

class DerivedCollect 
{
    DerivedCollect(
        const IGCollect& inputCollect,
        Handle handle) :
        _partHandles(std::make_shared<std::vector<Handle>()),
        _currUnmanaged(_partHandles),
        _extUnmanaged(_partHandles)
    {
        _partHandles->emplace_back(HandleManager::GetPHandle(handle));

        for (const auto& it : inputCollect.GetPartHandles())
        {
            _partHandles->emplace_back(it);
        }
    }

private:
    std::shared_ptr<std::vector<Handle>> _partHandles;
    UnmanagedCollect _currUnmanaged;
    UnmanagedCollect _extUnmanaged;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...