Home > Software design >  How do I assign an arbitrary value to a unique_ptr?
How do I assign an arbitrary value to a unique_ptr?

Time:09-07

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);

CodePudding user response:

You can combine std::unqiue_ptr with std::optional for this:

std::unique_ptr<std::optional<int>> p;
assert(!p);
p = std::make_unique<std::optional<int>>(std::nullopt);
assert(p);
assert(!(*p));

CodePudding user response:

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();
  • Related