C++ copy constructor called at returnIn which situations is the C++ copy constructor called?What are the differences between a pointer variable and a reference variable in C++?Why don't C++ compilers define operator== and operator!=?What is the lifetime of a static variable in a C++ function?Can I call a constructor from another constructor (do constructor chaining) in C++?Inheriting constructorsHow can I profile C++ code running on Linux?The Definitive C++ Book Guide and ListWhen to use virtual destructors?What is the “-->” operator in C++?What is the copy-and-swap idiom?

How to convince somebody that he is fit for something else, but not this job?

Is there any evidence that Cleopatra and Caesarion considered fleeing to India to escape the Romans?

Has any country ever had 2 former presidents in jail simultaneously?

"before" and "want" for the same systemd service?

Why do ¬, ∀ and ∃ have the same precedence?

GCD of cubic polynomials

Why is it that I can sometimes guess the next note?

A Trivial Diagnosis

Does the reader need to like the PoV character?

Circuit Analysis: Obtaining Close Loop OP - AMP Transfer function

Unable to get dependencies from jcenter with a new project

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

What (the heck) is a Super Worm Equinox Moon?

Why does Carol not get rid of the Kree symbol on her suit when she changes its colours?

In a multiple cat home, how many litter boxes should you have?

Giving feedback to someone without sounding prejudiced

How can ping know if my host is down

What is the English pronunciation of "pain au chocolat"?

Biological Blimps: Propulsion

Does Doodling or Improvising on the Piano Have Any Benefits?

What is Cash Advance APR?

Why Shazam when there is already Superman?

Does grappling negate Mirror Image?

Is this part of the description of the Archfey warlock's Misty Escape feature redundant?



C++ copy constructor called at return


In which situations is the C++ copy constructor called?What are the differences between a pointer variable and a reference variable in C++?Why don't C++ compilers define operator== and operator!=?What is the lifetime of a static variable in a C++ function?Can I call a constructor from another constructor (do constructor chaining) in C++?Inheriting constructorsHow can I profile C++ code running on Linux?The Definitive C++ Book Guide and ListWhen to use virtual destructors?What is the “-->” operator in C++?What is the copy-and-swap idiom?













6















error: use of deleted function 'A::A(const A&)'
return tmp;
^~~


Why is the copy constructor called only when there is a virtual destructor in A? How to avoid this?



struct B ;

struct A
std::unique_ptr<B> x;
virtual ~A() = default;
;

A f()
A tmp;
return tmp;










share|improve this question









New contributor




Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • At the moment, I can't verify that snippet because there's no B given.

    – Tzalumen
    1 hour ago











  • see: In which situations is the C++ copy constructor called?

    – kmdreko
    59 mins ago






  • 2





    C++ handles objects different than C#/Java. When an instance goes out of scope (tmp here) its destructor must be called. Therefore, when you return tmp then you're asking it to make a copy of tmp to be return to whomever calls the function. Once copied, tmp will be destroyed and its copy will be available for use.

    – Everyone
    59 mins ago















6















error: use of deleted function 'A::A(const A&)'
return tmp;
^~~


Why is the copy constructor called only when there is a virtual destructor in A? How to avoid this?



struct B ;

struct A
std::unique_ptr<B> x;
virtual ~A() = default;
;

A f()
A tmp;
return tmp;










share|improve this question









New contributor




Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • At the moment, I can't verify that snippet because there's no B given.

    – Tzalumen
    1 hour ago











  • see: In which situations is the C++ copy constructor called?

    – kmdreko
    59 mins ago






  • 2





    C++ handles objects different than C#/Java. When an instance goes out of scope (tmp here) its destructor must be called. Therefore, when you return tmp then you're asking it to make a copy of tmp to be return to whomever calls the function. Once copied, tmp will be destroyed and its copy will be available for use.

    – Everyone
    59 mins ago













6












6








6








error: use of deleted function 'A::A(const A&)'
return tmp;
^~~


Why is the copy constructor called only when there is a virtual destructor in A? How to avoid this?



struct B ;

struct A
std::unique_ptr<B> x;
virtual ~A() = default;
;

A f()
A tmp;
return tmp;










share|improve this question









New contributor




Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












error: use of deleted function 'A::A(const A&)'
return tmp;
^~~


Why is the copy constructor called only when there is a virtual destructor in A? How to avoid this?



struct B ;

struct A
std::unique_ptr<B> x;
virtual ~A() = default;
;

A f()
A tmp;
return tmp;







c++






share|improve this question









New contributor




Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 10 mins ago







Sobuch













New contributor




Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 1 hour ago









SobuchSobuch

335




335




New contributor




Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Sobuch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • At the moment, I can't verify that snippet because there's no B given.

    – Tzalumen
    1 hour ago











  • see: In which situations is the C++ copy constructor called?

    – kmdreko
    59 mins ago






  • 2





    C++ handles objects different than C#/Java. When an instance goes out of scope (tmp here) its destructor must be called. Therefore, when you return tmp then you're asking it to make a copy of tmp to be return to whomever calls the function. Once copied, tmp will be destroyed and its copy will be available for use.

    – Everyone
    59 mins ago

















  • At the moment, I can't verify that snippet because there's no B given.

    – Tzalumen
    1 hour ago











  • see: In which situations is the C++ copy constructor called?

    – kmdreko
    59 mins ago






  • 2





    C++ handles objects different than C#/Java. When an instance goes out of scope (tmp here) its destructor must be called. Therefore, when you return tmp then you're asking it to make a copy of tmp to be return to whomever calls the function. Once copied, tmp will be destroyed and its copy will be available for use.

    – Everyone
    59 mins ago
















At the moment, I can't verify that snippet because there's no B given.

– Tzalumen
1 hour ago





At the moment, I can't verify that snippet because there's no B given.

– Tzalumen
1 hour ago













see: In which situations is the C++ copy constructor called?

– kmdreko
59 mins ago





see: In which situations is the C++ copy constructor called?

– kmdreko
59 mins ago




2




2





C++ handles objects different than C#/Java. When an instance goes out of scope (tmp here) its destructor must be called. Therefore, when you return tmp then you're asking it to make a copy of tmp to be return to whomever calls the function. Once copied, tmp will be destroyed and its copy will be available for use.

– Everyone
59 mins ago





C++ handles objects different than C#/Java. When an instance goes out of scope (tmp here) its destructor must be called. Therefore, when you return tmp then you're asking it to make a copy of tmp to be return to whomever calls the function. Once copied, tmp will be destroyed and its copy will be available for use.

– Everyone
59 mins ago












1 Answer
1






active

oldest

votes


















15














virtual ~A() = default; is a user declared destructor. Because of that, A no longer has a move constructor. That means return tmp; can't move tmp and since tmp is not copyable, you get a compiler error.



There are two ways you can fix this. You can add a move constructor like



struct A
std::unique_ptr<B> x;

A() = default; // you have to add this since the move constructor was added
A(A&&) = default; // defaulted move
virtual ~A() = default;
;


or you can create a base class that has the virtual destructor and inherit from that like



struct C 
virtual ~C() = default;
;

struct A : C
std::unique_ptr<B> x;
;





share|improve this answer




















  • 4





    Better to follow the Rule of Zero/Five. Either add all of (copy ctor, move ctor, copy assignment, move assignment, destructor) or add none of them. In this example, none of them are necessary.

    – 0x5453
    54 mins ago






  • 1





    @0x5453 Unless this is a parent class and the OP wants the derived classes to get destroyed properly. You need a virtual destructor if you have polymorphism.

    – NathanOliver
    53 mins ago






  • 2





    @Tzalumen no delete is required (because that's what the unique pointer does for you), but a virtual destructor is required so that the unique pointer won't have UB.

    – eerorika
    47 mins ago







  • 2





    @Tzalumen If you delete an object of class X through a pointer to a base class of X and that base class doesn't have a virtual dtor, it's Undefined Behaviour. Regardless of what the destructor does.

    – Angew
    46 mins ago






  • 2





    @Tzalumen If you have polymorphism, you must have a virtual destructor. If you don't the destructor for the derived class won't be called and you have UB.

    – NathanOliver
    46 mins 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
);



);






Sobuch is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55288708%2fc-copy-constructor-called-at-return%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









15














virtual ~A() = default; is a user declared destructor. Because of that, A no longer has a move constructor. That means return tmp; can't move tmp and since tmp is not copyable, you get a compiler error.



There are two ways you can fix this. You can add a move constructor like



struct A
std::unique_ptr<B> x;

A() = default; // you have to add this since the move constructor was added
A(A&&) = default; // defaulted move
virtual ~A() = default;
;


or you can create a base class that has the virtual destructor and inherit from that like



struct C 
virtual ~C() = default;
;

struct A : C
std::unique_ptr<B> x;
;





share|improve this answer




















  • 4





    Better to follow the Rule of Zero/Five. Either add all of (copy ctor, move ctor, copy assignment, move assignment, destructor) or add none of them. In this example, none of them are necessary.

    – 0x5453
    54 mins ago






  • 1





    @0x5453 Unless this is a parent class and the OP wants the derived classes to get destroyed properly. You need a virtual destructor if you have polymorphism.

    – NathanOliver
    53 mins ago






  • 2





    @Tzalumen no delete is required (because that's what the unique pointer does for you), but a virtual destructor is required so that the unique pointer won't have UB.

    – eerorika
    47 mins ago







  • 2





    @Tzalumen If you delete an object of class X through a pointer to a base class of X and that base class doesn't have a virtual dtor, it's Undefined Behaviour. Regardless of what the destructor does.

    – Angew
    46 mins ago






  • 2





    @Tzalumen If you have polymorphism, you must have a virtual destructor. If you don't the destructor for the derived class won't be called and you have UB.

    – NathanOliver
    46 mins ago
















15














virtual ~A() = default; is a user declared destructor. Because of that, A no longer has a move constructor. That means return tmp; can't move tmp and since tmp is not copyable, you get a compiler error.



There are two ways you can fix this. You can add a move constructor like



struct A
std::unique_ptr<B> x;

A() = default; // you have to add this since the move constructor was added
A(A&&) = default; // defaulted move
virtual ~A() = default;
;


or you can create a base class that has the virtual destructor and inherit from that like



struct C 
virtual ~C() = default;
;

struct A : C
std::unique_ptr<B> x;
;





share|improve this answer




















  • 4





    Better to follow the Rule of Zero/Five. Either add all of (copy ctor, move ctor, copy assignment, move assignment, destructor) or add none of them. In this example, none of them are necessary.

    – 0x5453
    54 mins ago






  • 1





    @0x5453 Unless this is a parent class and the OP wants the derived classes to get destroyed properly. You need a virtual destructor if you have polymorphism.

    – NathanOliver
    53 mins ago






  • 2





    @Tzalumen no delete is required (because that's what the unique pointer does for you), but a virtual destructor is required so that the unique pointer won't have UB.

    – eerorika
    47 mins ago







  • 2





    @Tzalumen If you delete an object of class X through a pointer to a base class of X and that base class doesn't have a virtual dtor, it's Undefined Behaviour. Regardless of what the destructor does.

    – Angew
    46 mins ago






  • 2





    @Tzalumen If you have polymorphism, you must have a virtual destructor. If you don't the destructor for the derived class won't be called and you have UB.

    – NathanOliver
    46 mins ago














15












15








15







virtual ~A() = default; is a user declared destructor. Because of that, A no longer has a move constructor. That means return tmp; can't move tmp and since tmp is not copyable, you get a compiler error.



There are two ways you can fix this. You can add a move constructor like



struct A
std::unique_ptr<B> x;

A() = default; // you have to add this since the move constructor was added
A(A&&) = default; // defaulted move
virtual ~A() = default;
;


or you can create a base class that has the virtual destructor and inherit from that like



struct C 
virtual ~C() = default;
;

struct A : C
std::unique_ptr<B> x;
;





share|improve this answer















virtual ~A() = default; is a user declared destructor. Because of that, A no longer has a move constructor. That means return tmp; can't move tmp and since tmp is not copyable, you get a compiler error.



There are two ways you can fix this. You can add a move constructor like



struct A
std::unique_ptr<B> x;

A() = default; // you have to add this since the move constructor was added
A(A&&) = default; // defaulted move
virtual ~A() = default;
;


or you can create a base class that has the virtual destructor and inherit from that like



struct C 
virtual ~C() = default;
;

struct A : C
std::unique_ptr<B> x;
;






share|improve this answer














share|improve this answer



share|improve this answer








edited 39 mins ago

























answered 56 mins ago









NathanOliverNathanOliver

96k16135209




96k16135209







  • 4





    Better to follow the Rule of Zero/Five. Either add all of (copy ctor, move ctor, copy assignment, move assignment, destructor) or add none of them. In this example, none of them are necessary.

    – 0x5453
    54 mins ago






  • 1





    @0x5453 Unless this is a parent class and the OP wants the derived classes to get destroyed properly. You need a virtual destructor if you have polymorphism.

    – NathanOliver
    53 mins ago






  • 2





    @Tzalumen no delete is required (because that's what the unique pointer does for you), but a virtual destructor is required so that the unique pointer won't have UB.

    – eerorika
    47 mins ago







  • 2





    @Tzalumen If you delete an object of class X through a pointer to a base class of X and that base class doesn't have a virtual dtor, it's Undefined Behaviour. Regardless of what the destructor does.

    – Angew
    46 mins ago






  • 2





    @Tzalumen If you have polymorphism, you must have a virtual destructor. If you don't the destructor for the derived class won't be called and you have UB.

    – NathanOliver
    46 mins ago













  • 4





    Better to follow the Rule of Zero/Five. Either add all of (copy ctor, move ctor, copy assignment, move assignment, destructor) or add none of them. In this example, none of them are necessary.

    – 0x5453
    54 mins ago






  • 1





    @0x5453 Unless this is a parent class and the OP wants the derived classes to get destroyed properly. You need a virtual destructor if you have polymorphism.

    – NathanOliver
    53 mins ago






  • 2





    @Tzalumen no delete is required (because that's what the unique pointer does for you), but a virtual destructor is required so that the unique pointer won't have UB.

    – eerorika
    47 mins ago







  • 2





    @Tzalumen If you delete an object of class X through a pointer to a base class of X and that base class doesn't have a virtual dtor, it's Undefined Behaviour. Regardless of what the destructor does.

    – Angew
    46 mins ago






  • 2





    @Tzalumen If you have polymorphism, you must have a virtual destructor. If you don't the destructor for the derived class won't be called and you have UB.

    – NathanOliver
    46 mins ago








4




4





Better to follow the Rule of Zero/Five. Either add all of (copy ctor, move ctor, copy assignment, move assignment, destructor) or add none of them. In this example, none of them are necessary.

– 0x5453
54 mins ago





Better to follow the Rule of Zero/Five. Either add all of (copy ctor, move ctor, copy assignment, move assignment, destructor) or add none of them. In this example, none of them are necessary.

– 0x5453
54 mins ago




1




1





@0x5453 Unless this is a parent class and the OP wants the derived classes to get destroyed properly. You need a virtual destructor if you have polymorphism.

– NathanOliver
53 mins ago





@0x5453 Unless this is a parent class and the OP wants the derived classes to get destroyed properly. You need a virtual destructor if you have polymorphism.

– NathanOliver
53 mins ago




2




2





@Tzalumen no delete is required (because that's what the unique pointer does for you), but a virtual destructor is required so that the unique pointer won't have UB.

– eerorika
47 mins ago






@Tzalumen no delete is required (because that's what the unique pointer does for you), but a virtual destructor is required so that the unique pointer won't have UB.

– eerorika
47 mins ago





2




2





@Tzalumen If you delete an object of class X through a pointer to a base class of X and that base class doesn't have a virtual dtor, it's Undefined Behaviour. Regardless of what the destructor does.

– Angew
46 mins ago





@Tzalumen If you delete an object of class X through a pointer to a base class of X and that base class doesn't have a virtual dtor, it's Undefined Behaviour. Regardless of what the destructor does.

– Angew
46 mins ago




2




2





@Tzalumen If you have polymorphism, you must have a virtual destructor. If you don't the destructor for the derived class won't be called and you have UB.

– NathanOliver
46 mins ago






@Tzalumen If you have polymorphism, you must have a virtual destructor. If you don't the destructor for the derived class won't be called and you have UB.

– NathanOliver
46 mins ago













Sobuch is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















Sobuch is a new contributor. Be nice, and check out our Code of Conduct.












Sobuch is a new contributor. Be nice, and check out our Code of Conduct.











Sobuch is a new contributor. Be nice, and check out our Code of Conduct.














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%2f55288708%2fc-copy-constructor-called-at-return%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

acmart: Multiple authors: all with same affiliation, one author an additional affiliationHow to Write Names of Multiple Authors with Shared Affiliation in ACM 2017 Template?Multiple authors with different primary affiliation, but same additional affiliationSame affiliation for all authors without extra packagesIOS-Book-Article.cls: one author with multiple affiliationacmart: Shared Author AffiliationMultiple authors with different primary affiliation, but same additional affiliationAuthor affiliation with only 1 authorAdding Multiple Authors with Different Affiliation in LaTeX ArticleLaTeX: Multiple authors stays on same lineHow to Label Multiple Authors with Same DescriptionHow to make two authors use the same affiliationTwo authors with same affiliation on finished front page

How to write “ä” and other umlauts and accented letters in bibliography?Accents in BibTeXSorting references with special characters alphabeticallyUse ae ligature in bibliographyEastern European nameInverted circumflex in BibTexBibTex, non-ascii initials and nameptr fproblems with accent in LatexHow to add a Ø to my bibliography from Jabref?References without accentsTroubles when trying to cite St“omer-Verlet in ”title" field of a bib entryComprehensive list of accented charactersHow to type the letter “i” with two dots (diaeresis) in math mode?Problem with glossary text and accented lettersSpecial character in bibliographyAccented letters, Unicode and LaTeX accentsHow to stop natbib from modifying bibliography styleCitation of a paper with non-standard characters by BibtexWrite accented characters to file using writeHow to group the bibliography alphabetically, if some surnames start with “accented” characters?How can I automatically capitalize significant words in my bibliography?

How to force a table into page width?How to make table spanning textwidthMaking table width fit into text widthTable with tabular, column type p grabbing available spaceMaking widths of tables equal to width of textblocklatex tabular width the same as the textwidthMake tabular span textwidth exactlySet width of table to be the whole line or a given portion of itIs the tabu package obsolete?What is the difference between tabular, tabular* and tabularx environments?How can i set the width of a table?Making table width fit into text widthTabular and grid typesettingMake table use page widthTable exceeds page widthtable width automatically to page widthHow to shrink table to page widthForce table column to be zero widthTable width exceeds the page widthTable extending beyond the page widthforce longtable to text width