Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::shared_ptr<T>: implicit constructor for rvalue pointer to T

I pretty much support the idea of making std::shared_ptr<T> constructor that accepts T * explicit. it helps to save sleepless night, when you are looking the reason on heap corruption. Scott Meyers gave a good explanation for this.


But... If I give it an rvalue pointer isn't this explicit? I could do things like:

/// (1)
std::shared_ptr<T> t = new T;

or

/// (2)
T * giveaway = new T;
std::shared_ptr<T> t = std::move(giveaway);

or a much more painful case from real life

/// (3)
void foo(std::shared_ptr<T> t);
/// ...
foo(new T);

As for me, all these cases are explicit enough.

Case (1) is a prvalue, I can't possibly screw myself up having two pointers. At least no more than using:

std::shared_ptr<T> t{new T};

Case (2) is pretty much explicit. It is agreed that after you have moved something its value becomes undefined. So using it is totally on you.

Case (3) is an rvalue again.


(Q1) It this is an overlook by standard committee?

(Q2) Is there a reason for this?

(Q3) Any chance for implicit constructor accepting rvalue to appear in C++14?

like image 954
GreenScape Avatar asked Sep 26 '14 07:09

GreenScape


1 Answers

There's a reason even giving an rvalue does not allow implicit construction of a smart-pointer from a raw-pointer:

It is not safe.

void foo(std::shared_ptr<T> t);
char buffer[42];
foo(buffer+7); // buffer+7 is a rvalue, and would implicitly convert!

Thus, to the other two parts of your question:

  1. It is not an oversight by the committee.

And

  1. It will not appear in a future C++-standard (Anyway, C++14 is out and it did not appear).
like image 159
Deduplicator Avatar answered Nov 15 '22 05:11

Deduplicator