相关文章推荐
奋斗的山楂  ·  js 导出svg-掘金·  1 年前    · 
阳刚的豆腐  ·  vue(2.x) ...·  1 年前    · 
威武的刺猬  ·  Docker ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

When I look at the documentation for new there is no version that takes a pointer. Thus:

  • What does new (this) mean?
  • What is it used for?
  • How can it be called like this if it is not listed in the documentation?
  • you haven't found it because that's the documentation for the new operator , and not for the expression: en.cppreference.com/w/cpp/language/new Karoly Horvath Mar 24, 2014 at 8:50 I don't think this question should be closed. It might be helpful for people to find an answer to my question if they do not know about placement new -- which they likely wouldn't if they had this question. Also, the question asks why it would be used in this situation. Thus, it is different than the possible duplicated flagged above. user2836797 Mar 24, 2014 at 9:01

    It is called "placement new", and the comments in your code snippet pretty much explain it:

    It constructs an object of type T without allocating memory for it, in the address specified in the parentheses.

    So what you're looking at is a copy assignment operator which first destroys the object being copied to (without freeing the memory), and then constructs a new one in the same memory address. (It is also a pretty bad idea to implement the operator in this manner, as pointed out in the comments)

    It's noteworthy that if the construction fails (throws an exception), the memory at *this will not contain a valid object, and future attempts to use the object (including any destructor call if the object goes out of scope or is delete d) will have Undefined Behaviour. Tony Delroy Mar 24, 2014 at 8:50 Also noteworthy, in a derived class (if the class does not prohibit derivation) the placement new in assignment operator may set up a vtable pointer to the wrong class, again with Undefined Behavior. Cheers and hth. - Alf Mar 24, 2014 at 9:08 @jalf: re "what you're looking at is a copy constructor which" should be "what you're looking at is a copy assignment operator which". Cheers and hth. - Alf Mar 24, 2014 at 9:11 And also noteworthy, nothing prevents you from calling this operator with an argument that has automatic storage. Which is a recipe for desaster. Damon Mar 24, 2014 at 18:13

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question . Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers .