Thread: std::unique_ptr/shared_ptr assignment semantics

  1. #1
    Registered User
    Join Date
    Oct 2006

    std::unique_ptr/shared_ptr assignment semantics

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

    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.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    You are trying to invoke a constructor, not an assignment operator.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    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.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2006
    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.

  4. #4
    Registered User
    Join Date
    Aug 2003
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. std::unique_ptr
    By KIBO in forum C++ Programming
    Replies: 4
    Last Post: 12-07-2010, 07:48 AM
  2. semantics question
    By elsparko in forum C++ Programming
    Replies: 1
    Last Post: 05-12-2010, 09:16 AM
  3. Crazy Assignment Operator Semantics
    By SevenThunders in forum C++ Programming
    Replies: 7
    Last Post: 01-22-2009, 01:08 PM
  4. semantics
    By anjana in forum Tech Board
    Replies: 4
    Last Post: 10-10-2006, 10:35 AM
  5. iterator semantics
    By CornedBee in forum C++ Programming
    Replies: 8
    Last Post: 01-10-2004, 12:21 PM