std::unique_ptr/shared_ptr assignment semantics

I'm a little confused by the fact that I can't do something like the following:

Code:

int x = 3;
std::unique_ptr<int> px = &3;
// or even more to the point
std::unique_ptr<int> px = new int(3);

the compiler complains that it can't convert int* to std::unique_ptr<int>. fair enough. however, when I derive a class from unique_ptr, and define an assignment operator to take a right-hand argument of pointer type, it continues to give me the same type of error. I'm just curious as to why the pointer is treated differently.

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.

so in this type of scenario, the compiler is implicitly invoking the constructor instead of the assignment operator? is that standard behavior, or implementation defined? it just seems more logical that it should invoke the assignment operator, since the code explicitly uses the assignment operator.

It is implicitly invoking the constructor yes. The reason std::unique_ptr can not be used in this way is because the constructor that would be invoked is declared explicit, and thus can not be used in this way. This is standard behaviour.