Overriding an object in memory with placement new Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live! Should we burninate the [wrap] tag?What uses are there for “placement new”?Method of derived class needs to downcast its parameterC++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?Overloading >> operator for a base classChoice for class designWhy should I use a pointer rather than the object itself?Copying Objects and its data members to another objectoverriding 'virtual void ' c++ errorWhy must we declare virtual methods as suchWhat are the new features in C++17?

Why did the IBM 650 use bi-quinary?

Why aren't air breathing engines used as small first stages

Dating a Former Employee

How can I (re)show post-installation notes?

Do I really need recursive chmod to restrict access to a folder?

Simplicity of the roots of a minimal polynomial

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

How widely used is the term Treppenwitz? Is it something that most Germans know?

Coloring maths inside a tcolorbox

How to prevent mathematica rounding extremely small numbers to zero?

Why did the rest of the Eastern Bloc not invade Yugoslavia?

Can I cast Passwall to drop an enemy into a 20-foot pit?

String `!23` is replaced with `docker` in command line

Can an alien society believe that their star system is the universe?

When is phishing education going too far?

Why didn't this character "real die" when they blew their stack out in Altered Carbon?

What are the halakhic considerations when it comes to crossing a picket line?

The logistics of corpse disposal

Why are Kinder Surprise Eggs illegal in the USA?

What is Arya's weapon design?

How do database operations (write, update, alter) on particular cell in a table are written to disk without overwriting entire file?

Is pollution the main cause of Notre Dame Cathedral's deterioration?

Fundamental Solution of the Pell Equation

Why do people hide their license plates in the EU?



Overriding an object in memory with placement new



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!
Should we burninate the [wrap] tag?What uses are there for “placement new”?Method of derived class needs to downcast its parameterC++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?Overloading >> operator for a base classChoice for class designWhy should I use a pointer rather than the object itself?Copying Objects and its data members to another objectoverriding 'virtual void ' c++ errorWhy must we declare virtual methods as suchWhat are the new features in C++17?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








12















I have an object which I want to 'transform' into another object. For this I am using a placement new on the first object which creates a new object of the other type on top of its own address.



Consider the following code:



#include <string>
#include <iostream>

class Animal
public:
virtual void voice() = 0;
virtual void transform(void *animal) = 0;
virtual ~Animal() = default;;
;

class Cat : public Animal
public:
std::string name = "CAT";
void voice() override
std::cout << "MEOW I am a " << name << std::endl;

void transform(void *animal) override

;

class Dog : public Animal
public:
std::string name = "DOG";
void voice() override
std::cout << "WOOF I am a " << name << std::endl;

void transform(void *animal) override
new(animal) Cat();

;


You can see that when a Dog is called with transform it creates a new Cat on top of the given address.

Next, I will call the Dog::transform with its own address:



#include <iostream>
#include "Animals.h"

int main()
Cat cat;
Dog dog;
std::cout << "Cat says: ";
cat.voice() ;
std::cout << "Dog says: ";
dog.voice();
dog.transform(&dog);
std::cout << "Dog says: ";
dog.voice();
std::cout << "Dog address says: ";
(&dog)->voice();
return 0;



The results of this is:



Cat says: MEOW I am a CAT
Dog says: WOOF I am a DOG
Dog says: WOOF I am a CAT
Dog address says: MEOW I am a CAT


My questions are:



  1. Is this operation considered safe, or does it leave the object in unstable state?

  2. After the transform I call dog.voice(). It correctly prints the name CAT (it is now a cat), but still writes WOOF I am a, even though I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.









share|improve this question



















  • 6





    I can't cite where in the standard it says that this isn't allowed, but I can say that I get "WOOF I am a CAT" in both of the bottom lines on my system, which is a pretty good indicator that this behavior is not portable.

    – Silvio Mayolo
    5 hours ago











  • If you need this behavior which I would describe as "The object will appear to change it's class", consider using the Gang of Four State Pattern: en.wikipedia.org/wiki/State_pattern

    – Reginald Blue
    3 hours ago

















12















I have an object which I want to 'transform' into another object. For this I am using a placement new on the first object which creates a new object of the other type on top of its own address.



Consider the following code:



#include <string>
#include <iostream>

class Animal
public:
virtual void voice() = 0;
virtual void transform(void *animal) = 0;
virtual ~Animal() = default;;
;

class Cat : public Animal
public:
std::string name = "CAT";
void voice() override
std::cout << "MEOW I am a " << name << std::endl;

void transform(void *animal) override

;

class Dog : public Animal
public:
std::string name = "DOG";
void voice() override
std::cout << "WOOF I am a " << name << std::endl;

void transform(void *animal) override
new(animal) Cat();

;


You can see that when a Dog is called with transform it creates a new Cat on top of the given address.

Next, I will call the Dog::transform with its own address:



#include <iostream>
#include "Animals.h"

int main()
Cat cat;
Dog dog;
std::cout << "Cat says: ";
cat.voice() ;
std::cout << "Dog says: ";
dog.voice();
dog.transform(&dog);
std::cout << "Dog says: ";
dog.voice();
std::cout << "Dog address says: ";
(&dog)->voice();
return 0;



The results of this is:



Cat says: MEOW I am a CAT
Dog says: WOOF I am a DOG
Dog says: WOOF I am a CAT
Dog address says: MEOW I am a CAT


My questions are:



  1. Is this operation considered safe, or does it leave the object in unstable state?

  2. After the transform I call dog.voice(). It correctly prints the name CAT (it is now a cat), but still writes WOOF I am a, even though I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.









share|improve this question



















  • 6





    I can't cite where in the standard it says that this isn't allowed, but I can say that I get "WOOF I am a CAT" in both of the bottom lines on my system, which is a pretty good indicator that this behavior is not portable.

    – Silvio Mayolo
    5 hours ago











  • If you need this behavior which I would describe as "The object will appear to change it's class", consider using the Gang of Four State Pattern: en.wikipedia.org/wiki/State_pattern

    – Reginald Blue
    3 hours ago













12












12








12


1






I have an object which I want to 'transform' into another object. For this I am using a placement new on the first object which creates a new object of the other type on top of its own address.



Consider the following code:



#include <string>
#include <iostream>

class Animal
public:
virtual void voice() = 0;
virtual void transform(void *animal) = 0;
virtual ~Animal() = default;;
;

class Cat : public Animal
public:
std::string name = "CAT";
void voice() override
std::cout << "MEOW I am a " << name << std::endl;

void transform(void *animal) override

;

class Dog : public Animal
public:
std::string name = "DOG";
void voice() override
std::cout << "WOOF I am a " << name << std::endl;

void transform(void *animal) override
new(animal) Cat();

;


You can see that when a Dog is called with transform it creates a new Cat on top of the given address.

Next, I will call the Dog::transform with its own address:



#include <iostream>
#include "Animals.h"

int main()
Cat cat;
Dog dog;
std::cout << "Cat says: ";
cat.voice() ;
std::cout << "Dog says: ";
dog.voice();
dog.transform(&dog);
std::cout << "Dog says: ";
dog.voice();
std::cout << "Dog address says: ";
(&dog)->voice();
return 0;



The results of this is:



Cat says: MEOW I am a CAT
Dog says: WOOF I am a DOG
Dog says: WOOF I am a CAT
Dog address says: MEOW I am a CAT


My questions are:



  1. Is this operation considered safe, or does it leave the object in unstable state?

  2. After the transform I call dog.voice(). It correctly prints the name CAT (it is now a cat), but still writes WOOF I am a, even though I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.









share|improve this question
















I have an object which I want to 'transform' into another object. For this I am using a placement new on the first object which creates a new object of the other type on top of its own address.



Consider the following code:



#include <string>
#include <iostream>

class Animal
public:
virtual void voice() = 0;
virtual void transform(void *animal) = 0;
virtual ~Animal() = default;;
;

class Cat : public Animal
public:
std::string name = "CAT";
void voice() override
std::cout << "MEOW I am a " << name << std::endl;

void transform(void *animal) override

;

class Dog : public Animal
public:
std::string name = "DOG";
void voice() override
std::cout << "WOOF I am a " << name << std::endl;

void transform(void *animal) override
new(animal) Cat();

;


You can see that when a Dog is called with transform it creates a new Cat on top of the given address.

Next, I will call the Dog::transform with its own address:



#include <iostream>
#include "Animals.h"

int main()
Cat cat;
Dog dog;
std::cout << "Cat says: ";
cat.voice() ;
std::cout << "Dog says: ";
dog.voice();
dog.transform(&dog);
std::cout << "Dog says: ";
dog.voice();
std::cout << "Dog address says: ";
(&dog)->voice();
return 0;



The results of this is:



Cat says: MEOW I am a CAT
Dog says: WOOF I am a DOG
Dog says: WOOF I am a CAT
Dog address says: MEOW I am a CAT


My questions are:



  1. Is this operation considered safe, or does it leave the object in unstable state?

  2. After the transform I call dog.voice(). It correctly prints the name CAT (it is now a cat), but still writes WOOF I am a, even though I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.






c++ placement-new






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 45 mins ago









John Kugelman

249k54407460




249k54407460










asked 5 hours ago









Guy YafeGuy Yafe

4431416




4431416







  • 6





    I can't cite where in the standard it says that this isn't allowed, but I can say that I get "WOOF I am a CAT" in both of the bottom lines on my system, which is a pretty good indicator that this behavior is not portable.

    – Silvio Mayolo
    5 hours ago











  • If you need this behavior which I would describe as "The object will appear to change it's class", consider using the Gang of Four State Pattern: en.wikipedia.org/wiki/State_pattern

    – Reginald Blue
    3 hours ago












  • 6





    I can't cite where in the standard it says that this isn't allowed, but I can say that I get "WOOF I am a CAT" in both of the bottom lines on my system, which is a pretty good indicator that this behavior is not portable.

    – Silvio Mayolo
    5 hours ago











  • If you need this behavior which I would describe as "The object will appear to change it's class", consider using the Gang of Four State Pattern: en.wikipedia.org/wiki/State_pattern

    – Reginald Blue
    3 hours ago







6




6





I can't cite where in the standard it says that this isn't allowed, but I can say that I get "WOOF I am a CAT" in both of the bottom lines on my system, which is a pretty good indicator that this behavior is not portable.

– Silvio Mayolo
5 hours ago





I can't cite where in the standard it says that this isn't allowed, but I can say that I get "WOOF I am a CAT" in both of the bottom lines on my system, which is a pretty good indicator that this behavior is not portable.

– Silvio Mayolo
5 hours ago













If you need this behavior which I would describe as "The object will appear to change it's class", consider using the Gang of Four State Pattern: en.wikipedia.org/wiki/State_pattern

– Reginald Blue
3 hours ago





If you need this behavior which I would describe as "The object will appear to change it's class", consider using the Gang of Four State Pattern: en.wikipedia.org/wiki/State_pattern

– Reginald Blue
3 hours ago












3 Answers
3






active

oldest

votes


















10















Does this operation considered safe, or does it leave the object in unstable state?




This operation is not safe and causes undefined behavior. Cat and Dog have non trivial destructors so before you can reuse the storage cat and dog have you have to call their destructor so the previous object is cleaned up correctly.




After the transform I call dog.voice(). I prints correctly the CAT name (it is now a cat), but still writes WOOF I am a, even tough I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.




Using dog.voice(); after dog.transform(&dog); is undefined behavior. Since you've reused its storage without destroying it, you have undefined behavior. Lets say you do destroy dog in transform to get rid of that bit of undefined behavior you still aren't out of the woods. Using dog after it has been destroyed is undefined behavior. What you would have to do is capture the pointer placement new returns and use that pointer from then on. You could also use std::launder on dog with a reinterpret_cast to the type you transformed it to but it's not worth since you lose all encapsulation.




You also need to make sure when using placement new that the object you are using is large enough for the object you are constructing. In this case it should be since the classes are the same but a static_assert comparing the sizes will guarantee that and stop the compilation if it is not true.






share|improve this answer
































    4














    You have at least three issues with this code:



    • There is no guarantee that when placement new is called the size of the object you are constructing your new object in is sufficient to hold the new object

    • You are not calling destructor of the object used as a placeholder

    • You use the Dog object after it's storage has been reused.





    share|improve this answer






























      3














      1) No, this is not safe for the following reasons:



      • The behavior is undefined and can be different for some compilers.

      • The allocated memory needs to be big enough to hold the newly created structure.

      • Some compilers might call the destructor of the original object even if it is virtual, which would lead to leaks and crashes.

      • In your code, the destructor of the original object is not called, so it can lead to memory leaks.

      2) I observed on MSVC2015 that dog.voice() will call Dog::voice without checking the actual virtual table. In the second case, it checks the virtual table, which has been modified to be Cat::voice. However, as experienced by other users, some other compiler might perform some optimizations and directly call the method that matches the declaration in all cases.






      share|improve this answer

























      • When you say behavior is not portable you need to explain why. The destructor is already virtual.

        – SergeyA
        5 hours ago












      • I meant that some compilers do not behave the same. "Undefined behavior" might be better. I'll edit the answer.

        – Gilles-Philippe Paillé
        5 hours ago











      • Do note there is a virtual destructor in the code in question

        – NathanOliver
        5 hours ago












      • @NathanOliver That's true. I was mentioning general rules that needs to be respected. I will make it clearer.

        – Gilles-Philippe Paillé
        5 hours ago











      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55711220%2foverriding-an-object-in-memory-with-placement-new%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      10















      Does this operation considered safe, or does it leave the object in unstable state?




      This operation is not safe and causes undefined behavior. Cat and Dog have non trivial destructors so before you can reuse the storage cat and dog have you have to call their destructor so the previous object is cleaned up correctly.




      After the transform I call dog.voice(). I prints correctly the CAT name (it is now a cat), but still writes WOOF I am a, even tough I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.




      Using dog.voice(); after dog.transform(&dog); is undefined behavior. Since you've reused its storage without destroying it, you have undefined behavior. Lets say you do destroy dog in transform to get rid of that bit of undefined behavior you still aren't out of the woods. Using dog after it has been destroyed is undefined behavior. What you would have to do is capture the pointer placement new returns and use that pointer from then on. You could also use std::launder on dog with a reinterpret_cast to the type you transformed it to but it's not worth since you lose all encapsulation.




      You also need to make sure when using placement new that the object you are using is large enough for the object you are constructing. In this case it should be since the classes are the same but a static_assert comparing the sizes will guarantee that and stop the compilation if it is not true.






      share|improve this answer





























        10















        Does this operation considered safe, or does it leave the object in unstable state?




        This operation is not safe and causes undefined behavior. Cat and Dog have non trivial destructors so before you can reuse the storage cat and dog have you have to call their destructor so the previous object is cleaned up correctly.




        After the transform I call dog.voice(). I prints correctly the CAT name (it is now a cat), but still writes WOOF I am a, even tough I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.




        Using dog.voice(); after dog.transform(&dog); is undefined behavior. Since you've reused its storage without destroying it, you have undefined behavior. Lets say you do destroy dog in transform to get rid of that bit of undefined behavior you still aren't out of the woods. Using dog after it has been destroyed is undefined behavior. What you would have to do is capture the pointer placement new returns and use that pointer from then on. You could also use std::launder on dog with a reinterpret_cast to the type you transformed it to but it's not worth since you lose all encapsulation.




        You also need to make sure when using placement new that the object you are using is large enough for the object you are constructing. In this case it should be since the classes are the same but a static_assert comparing the sizes will guarantee that and stop the compilation if it is not true.






        share|improve this answer



























          10












          10








          10








          Does this operation considered safe, or does it leave the object in unstable state?




          This operation is not safe and causes undefined behavior. Cat and Dog have non trivial destructors so before you can reuse the storage cat and dog have you have to call their destructor so the previous object is cleaned up correctly.




          After the transform I call dog.voice(). I prints correctly the CAT name (it is now a cat), but still writes WOOF I am a, even tough I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.




          Using dog.voice(); after dog.transform(&dog); is undefined behavior. Since you've reused its storage without destroying it, you have undefined behavior. Lets say you do destroy dog in transform to get rid of that bit of undefined behavior you still aren't out of the woods. Using dog after it has been destroyed is undefined behavior. What you would have to do is capture the pointer placement new returns and use that pointer from then on. You could also use std::launder on dog with a reinterpret_cast to the type you transformed it to but it's not worth since you lose all encapsulation.




          You also need to make sure when using placement new that the object you are using is large enough for the object you are constructing. In this case it should be since the classes are the same but a static_assert comparing the sizes will guarantee that and stop the compilation if it is not true.






          share|improve this answer
















          Does this operation considered safe, or does it leave the object in unstable state?




          This operation is not safe and causes undefined behavior. Cat and Dog have non trivial destructors so before you can reuse the storage cat and dog have you have to call their destructor so the previous object is cleaned up correctly.




          After the transform I call dog.voice(). I prints correctly the CAT name (it is now a cat), but still writes WOOF I am a, even tough I would have thought that it should call the Cat's voice method? (You can see is that I call the same method but by the address ((&dog)->voice()), everything is working properly.




          Using dog.voice(); after dog.transform(&dog); is undefined behavior. Since you've reused its storage without destroying it, you have undefined behavior. Lets say you do destroy dog in transform to get rid of that bit of undefined behavior you still aren't out of the woods. Using dog after it has been destroyed is undefined behavior. What you would have to do is capture the pointer placement new returns and use that pointer from then on. You could also use std::launder on dog with a reinterpret_cast to the type you transformed it to but it's not worth since you lose all encapsulation.




          You also need to make sure when using placement new that the object you are using is large enough for the object you are constructing. In this case it should be since the classes are the same but a static_assert comparing the sizes will guarantee that and stop the compilation if it is not true.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 43 mins ago









          John Kugelman

          249k54407460




          249k54407460










          answered 5 hours ago









          NathanOliverNathanOliver

          99.1k16138219




          99.1k16138219























              4














              You have at least three issues with this code:



              • There is no guarantee that when placement new is called the size of the object you are constructing your new object in is sufficient to hold the new object

              • You are not calling destructor of the object used as a placeholder

              • You use the Dog object after it's storage has been reused.





              share|improve this answer



























                4














                You have at least three issues with this code:



                • There is no guarantee that when placement new is called the size of the object you are constructing your new object in is sufficient to hold the new object

                • You are not calling destructor of the object used as a placeholder

                • You use the Dog object after it's storage has been reused.





                share|improve this answer

























                  4












                  4








                  4







                  You have at least three issues with this code:



                  • There is no guarantee that when placement new is called the size of the object you are constructing your new object in is sufficient to hold the new object

                  • You are not calling destructor of the object used as a placeholder

                  • You use the Dog object after it's storage has been reused.





                  share|improve this answer













                  You have at least three issues with this code:



                  • There is no guarantee that when placement new is called the size of the object you are constructing your new object in is sufficient to hold the new object

                  • You are not calling destructor of the object used as a placeholder

                  • You use the Dog object after it's storage has been reused.






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 5 hours ago









                  SergeyASergeyA

                  45.1k53990




                  45.1k53990





















                      3














                      1) No, this is not safe for the following reasons:



                      • The behavior is undefined and can be different for some compilers.

                      • The allocated memory needs to be big enough to hold the newly created structure.

                      • Some compilers might call the destructor of the original object even if it is virtual, which would lead to leaks and crashes.

                      • In your code, the destructor of the original object is not called, so it can lead to memory leaks.

                      2) I observed on MSVC2015 that dog.voice() will call Dog::voice without checking the actual virtual table. In the second case, it checks the virtual table, which has been modified to be Cat::voice. However, as experienced by other users, some other compiler might perform some optimizations and directly call the method that matches the declaration in all cases.






                      share|improve this answer

























                      • When you say behavior is not portable you need to explain why. The destructor is already virtual.

                        – SergeyA
                        5 hours ago












                      • I meant that some compilers do not behave the same. "Undefined behavior" might be better. I'll edit the answer.

                        – Gilles-Philippe Paillé
                        5 hours ago











                      • Do note there is a virtual destructor in the code in question

                        – NathanOliver
                        5 hours ago












                      • @NathanOliver That's true. I was mentioning general rules that needs to be respected. I will make it clearer.

                        – Gilles-Philippe Paillé
                        5 hours ago















                      3














                      1) No, this is not safe for the following reasons:



                      • The behavior is undefined and can be different for some compilers.

                      • The allocated memory needs to be big enough to hold the newly created structure.

                      • Some compilers might call the destructor of the original object even if it is virtual, which would lead to leaks and crashes.

                      • In your code, the destructor of the original object is not called, so it can lead to memory leaks.

                      2) I observed on MSVC2015 that dog.voice() will call Dog::voice without checking the actual virtual table. In the second case, it checks the virtual table, which has been modified to be Cat::voice. However, as experienced by other users, some other compiler might perform some optimizations and directly call the method that matches the declaration in all cases.






                      share|improve this answer

























                      • When you say behavior is not portable you need to explain why. The destructor is already virtual.

                        – SergeyA
                        5 hours ago












                      • I meant that some compilers do not behave the same. "Undefined behavior" might be better. I'll edit the answer.

                        – Gilles-Philippe Paillé
                        5 hours ago











                      • Do note there is a virtual destructor in the code in question

                        – NathanOliver
                        5 hours ago












                      • @NathanOliver That's true. I was mentioning general rules that needs to be respected. I will make it clearer.

                        – Gilles-Philippe Paillé
                        5 hours ago













                      3












                      3








                      3







                      1) No, this is not safe for the following reasons:



                      • The behavior is undefined and can be different for some compilers.

                      • The allocated memory needs to be big enough to hold the newly created structure.

                      • Some compilers might call the destructor of the original object even if it is virtual, which would lead to leaks and crashes.

                      • In your code, the destructor of the original object is not called, so it can lead to memory leaks.

                      2) I observed on MSVC2015 that dog.voice() will call Dog::voice without checking the actual virtual table. In the second case, it checks the virtual table, which has been modified to be Cat::voice. However, as experienced by other users, some other compiler might perform some optimizations and directly call the method that matches the declaration in all cases.






                      share|improve this answer















                      1) No, this is not safe for the following reasons:



                      • The behavior is undefined and can be different for some compilers.

                      • The allocated memory needs to be big enough to hold the newly created structure.

                      • Some compilers might call the destructor of the original object even if it is virtual, which would lead to leaks and crashes.

                      • In your code, the destructor of the original object is not called, so it can lead to memory leaks.

                      2) I observed on MSVC2015 that dog.voice() will call Dog::voice without checking the actual virtual table. In the second case, it checks the virtual table, which has been modified to be Cat::voice. However, as experienced by other users, some other compiler might perform some optimizations and directly call the method that matches the declaration in all cases.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 1 hour ago

























                      answered 5 hours ago









                      Gilles-Philippe PailléGilles-Philippe Paillé

                      55210




                      55210












                      • When you say behavior is not portable you need to explain why. The destructor is already virtual.

                        – SergeyA
                        5 hours ago












                      • I meant that some compilers do not behave the same. "Undefined behavior" might be better. I'll edit the answer.

                        – Gilles-Philippe Paillé
                        5 hours ago











                      • Do note there is a virtual destructor in the code in question

                        – NathanOliver
                        5 hours ago












                      • @NathanOliver That's true. I was mentioning general rules that needs to be respected. I will make it clearer.

                        – Gilles-Philippe Paillé
                        5 hours ago

















                      • When you say behavior is not portable you need to explain why. The destructor is already virtual.

                        – SergeyA
                        5 hours ago












                      • I meant that some compilers do not behave the same. "Undefined behavior" might be better. I'll edit the answer.

                        – Gilles-Philippe Paillé
                        5 hours ago











                      • Do note there is a virtual destructor in the code in question

                        – NathanOliver
                        5 hours ago












                      • @NathanOliver That's true. I was mentioning general rules that needs to be respected. I will make it clearer.

                        – Gilles-Philippe Paillé
                        5 hours ago
















                      When you say behavior is not portable you need to explain why. The destructor is already virtual.

                      – SergeyA
                      5 hours ago






                      When you say behavior is not portable you need to explain why. The destructor is already virtual.

                      – SergeyA
                      5 hours ago














                      I meant that some compilers do not behave the same. "Undefined behavior" might be better. I'll edit the answer.

                      – Gilles-Philippe Paillé
                      5 hours ago





                      I meant that some compilers do not behave the same. "Undefined behavior" might be better. I'll edit the answer.

                      – Gilles-Philippe Paillé
                      5 hours ago













                      Do note there is a virtual destructor in the code in question

                      – NathanOliver
                      5 hours ago






                      Do note there is a virtual destructor in the code in question

                      – NathanOliver
                      5 hours ago














                      @NathanOliver That's true. I was mentioning general rules that needs to be respected. I will make it clearer.

                      – Gilles-Philippe Paillé
                      5 hours ago





                      @NathanOliver That's true. I was mentioning general rules that needs to be respected. I will make it clearer.

                      – Gilles-Philippe Paillé
                      5 hours ago

















                      draft saved

                      draft discarded
















































                      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.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55711220%2foverriding-an-object-in-memory-with-placement-new%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Era Viking Índice Início da Era Viquingue | Cotidiano | Sociedade | Língua | Religião | A arte | As primeiras cidades | As viagens dos viquingues | Viquingues do Oeste e Leste | Fim da Era Viquingue | Fontes históricas | Referências Bibliografia | Ligações externas | Menu de navegação«Sverige då!»«Handel I vikingetid»«O que é Nórdico Antigo»Mito, magia e religião na volsunga saga Um olhar sobre a trajetória mítica do herói sigurd«Bonden var den verklige vikingen»«Vikingatiden»«Vikingatiden»«Vinland»«Guerreiras de Óðinn: As Valkyrjor na Mitologia Viking»1519-9053«Esculpindo símbolos e seres: A arte viking em pedras rúnicas»1679-9313Historia - Tema: VikingarnaAventura e Magia no Mundo das Sagas IslandesasEra Vikinge

                      What's the metal clinking sound at the end of credits in Avengers: Endgame?What makes Thanos so strong in Avengers: Endgame?Who is the character that appears at the end of Endgame?What happens to Mjolnir (Thor's hammer) at the end of Endgame?The People's Ages in Avengers: EndgameWhat did Nebula do in Avengers: Endgame?Messing with time in the Avengers: Endgame climaxAvengers: Endgame timelineWhat are the time-travel rules in Avengers Endgame?Why use this song in Avengers: Endgame Opening Logo Sequence?Peggy's age in Avengers Endgame

                      Are there legal definitions of ethnicities/races? The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Legal definitions in the United StatesAre there truly legal limits on US interest rates?Are gender identity and sexual orientation federally protected?Why is there an apparent legal bias against digital services?What limits are there to the powers of individual judges in the United States legal system?Are women only scholarships legal under Irish / EU law?Is the term “race” defined by Public Law enacted by Congress of the United StatesIs there a legal definition of race in the US?Neighbors are spying for landlord on Renters is it legal?Are Protected Classes Bi-directional?