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

0

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!

c++
memory
constructor
shared-ptr
list-initialization
asked on Stack Overflow Jan 12, 2021 by PythonLinski • edited Jan 12, 2021 by PythonLinski

2 Answers

2

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;
};
answered on Stack Overflow Jan 12, 2021 by molbdnilo
-1

The assignment of _currUnmanaged and _extUnmanaged should be moved within the constructor

answered on Stack Overflow Jan 12, 2021 by girdhar

User contributions licensed under CC BY-SA 3.0