std::unique_ptr/shared_ptr assignment semantics

This is a discussion on std::unique_ptr/shared_ptr assignment semantics within the C++ Programming forums, part of the General Programming Boards category; I'm a little confused by the fact that I can't do something like the following: Code: int x = 3; ...

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    2,421

    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.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,745
    You are trying to invoke a constructor, not an assignment operator.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    2,421
    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
    Posts
    1,205
    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, 06: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, 12: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, 11:21 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21