简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM