C++ copy constructor

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Guys, consider the following short program example:

 

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


using namespace std;

class myclass {
public:
	myclass();
	myclass(const myclass &o);
	myclass f(myclass);
};

myclass::myclass() {
	cout << "Costructing Normally\n";
}

myclass::myclass(const myclass &o) {
	cout << "Constructor Copy\n";
}


myclass myclass::f(myclass obj) {

	return obj;
}

void main() {

	myclass obj;
	obj = obj.f(obj);

	while(1);
}

It first creates an object using, "Costructing Normally" for "myclass obj;".

Next, its uses the "copy constructor" when passing the obj to obj.f

 

So far so good, but why does it use the copy constructor again when passing the object back?

This topic has a solution.
Last Edited: Wed. Jan 8, 2020 - 10:23 PM
This reply has been marked as the solution. 
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

okay, when a object is returned a temporary copy is created.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

That is not usually the case. In your case, you've created a scenario where copy/move elision is specifically not allowed (returning a parameter).

 

I don't know what you are using to learn C++, but I would highly suggest that you use Bjarne Stroustrup's Programming: Principles and Practices Using C++ (most recent edition covers C++11 and some of C++14), and A Tour of C++ (most recent edition covers up through C++17). From there, Scott Meyers' Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14 is a must read. Robert Seacord's Secure Coding in C and C++ is also a must read for anyone using C or C++ for development (most if not all of this information can also be found online). Cristopher Kormanyos' Real-Time C++: Efficient Object-Oriented and Template Microcontroller Programming provides a good introduction to techniques for using C++ with microcontrollers.

github.com/apcountryman/build-avr-gcc: a script for building avr-gcc

github.com/apcountryman/toolchain-avr-gcc: a CMake toolchain for cross compiling for the Atmel AVR family of microcontrollers