Mends.One

RValue Pointers?

C++11, C++, Rvalue

How can I tell if a pointer is an RValue or I don't know what I'm talking about.. This really ridiculous idea popped into my head while drinking a beer..

What if you have stupid programmer/user..

Assume you have the following class:

template<typename T>
class Container
{
    private:
        std::vector<T> Storage;
    public:
        Container(T Anything) : Storage() {Storage.push_back(Anything);}
}

and the user does:

Container<Object*> C(new Object(Params));

Then how can I delete it? I want to be able to tell the difference between the above and the below:

Object* O = new Object(Params);
Container<Object*> C(O);

I just want to know. I know that the first example obviously should not be used but let's assume that it will be or that I want to detect leaking code like that and delete them.

How can this be done? Is that an RValue pointer? What do I call that?

-1
B
Brandon
Jump to: Answer 1

Answers (1)

Easiest and correct thing would be to wrap naked pointers in some resource container like shared_ptr.

3
V
Vishal Kumar

Comments:

Brandon said:
No because then you'd be deleting a managed pointer. You don't want to delete every pointer.. only the stupid leaking ones.
ildjarn said:
@CantChooseUsernames : If it's shared, it will only be deleted when every instance goes out of scope.
Vishal Kumar said:
shared_poiner only deletes when resource count reaches zero. auto_ptr or unique_poiner gives single resource ownership.
Benjamin Lindley said:
@CantChooseUsernames: Yes, if the user is an idiot, and does something totally stupid and non-intuitive like calling delete on a pointer that was passed to a shared_ptr, it will break. What are you trying to do, protect users from every conceivable error that they could possibly make? Even if you could "fix" this "problem", bad programmers will find something else to mess up.
Benjamin Lindley said:
@CantChooseUsernames: Oh, nevermind. The problem in your example there is your class constructor. You should not take a raw pointer in and then pass it to a shared_ptr. That's a transfer of ownership, which should start with an object that ensures that the caller actually has ownership. That is, the constructor should take a shared_ptr and store a copy of it.

Related Questions