Cort Ammon
Cort Ammon

Reputation: 10863

Can I prevent the creation of non-temporary instances of my C++ class?

I'm building an expression-like class system. I would like to take advantage of the lifespan rules for temporary variables to avoid storing the ensure expression in a giant ugly templated class with unreadable error messages.

Of course, if the user cleverly saves off one of my expression objects in a variable, they can accidentally create dangling temporaries.

Is there a way to prevent the user from being able to create a local variable to hold onto one of my expression instances, so that they can never be surprised by a temporary that they thought was captured but was actually just temporary?

Upvotes: 2

Views: 155

Answers (1)

Caleth
Caleth

Reputation: 62636

I don't know of a way of stopping someone from having a local of a type you allow them to create, but you can make it mostly unusable by && qualifying all of it's members.

That won't stop a determined attempt to misuse it, as they can always std::move it, but it should avoid accidents.

Upvotes: 2

Related Questions