Search code examples
c++unit-testingunique-ptr

How do I assign an arbitrary value to a unique_ptr?


Is there a way to assign an arbitrary value to a unique_ptr?

Let's say I have some unique_ptr of an object. For testing purposes, I want to have this unique_ptr to be != nullptr, and/or pObj.get() != 0 without having to construct the object.

std::unique_ptr<someObj> pObj;
assert(!pObj);

// OK, but not what I want
// pObj = std::make_unique<someObj>();
// assert(pObj);

// Assign a "fake" object at an arbitrary memory location have have the assertion to be true.
pObj = 1;
assert(pObj);

Solution

  • Summarize the answers given in the comments of the question.

    The new code has to look like this:

    std::unique_ptr<someObj> pObj;
    assert(!pObj);
    
    // Assign a "fake" object at an arbitrary memory location
    pObj.reset((someObj *)1);
    assert(pObj);
    
    // release before unique_ptr is destructed!
    // Else we would get an Segmentation Fault
    // when the "fake" objects destructor is called by the unique_ptr.
    pObj.release();