Why is copy-constructor not called in this case? - c++

I encountered a code snippet and thought that it would call copy-constructor but in contrast , it simply called normal constructor . Below is the code
#include <iostream>
using namespace std;
class B
{
public:
B(const char* str = "\0")
{
cout << "Constructor called" << endl;
}
B(const B &b)
{
cout << "Copy constructor called" << endl;
}
};
int main()
{
B ob = "copy me";
return 0;
}

What you've discovered that B ob = "copy me"; notionally creates a B from the literal and then copy constructs ob, but that the compiler is allowed to elide the copy and construct directory into ob. g++ even elides the copy with no optimization enabled at all.
You can observe that this is the case by making your copy constructor private: The code will fail to compile even though the compiler won't actually use the copy constructor (the standard requires that copy constructors be accessible even when the call is elided).

Related

copy initialization : why move or copy constructor was not called even if copy-elision is turned off?

My question is different because I may "know" copy-elision. I am learning copy initialization. However,the following code confused me because I have already turned off the copy-elision using -fno-elide-contructors -O0 option.
#include <iostream>
using namespace std;
class test{
public :
test(int a_, int b_) : a{a_}, b{b_} {}
test(const test& other)
{
cout << "copy constructor" << endl;
}
test& operator=(const test& other)
{
cout << "copy assignment" << endl;
return *this;
}
test(test&& other)
{
cout << "move constructor" << endl;
}
test& operator=(test&& other)
{
cout <<"move assignment" << endl;
return *this;
}
private :
int a;
int b;
};
test show_elide_constructors()
{
return test{1,2};
}
int main()
{
cout << "**show elide constructors**" <<endl;
show_elide_constructors();
cout << "**what is this?**" <<endl;
test instance = {1,2};//why neither move constructor nor copy constructor is not called?
cout << "**show move assignment**" <<endl;
instance = {3,4};
return 0;
}
I first build with the command:
g++ -std=c++11 -fno-elide-constructors -O0 main.cpp -o main and I got the result as following:
**show elide constructors**
move constructor
**what is this?**
**show move assignment**
move assignment
Then I built with command without -fno-elide-constructor -O0 option to attest that g++ indeed turned off the optimization in my previous build.
So, why test instance = {1,2} does not call copy constructor or move constructor? Isn't a temp object created from the implicit conversion? And instance is supposed to be initialized by that temp object?
why test instance = {1,2} does not call copy constructor or move constructor?
It shouldn't. test instance = {1,2} is copy-list-initialization, as the effect, the appropriate constructor (i.e. test::test(int, int)) is used to construct the object instance directly. No needs to construct a temporary and call copy/move constructor here.
OK. I add some supplementary information here.
: Copy initialization, List initialization.
So T object = {other} is indeed copy initialization until c++11, which consider it as list initialization.
BTW, if the constructor is explicit, the call would fail.

Copy constructor not called when initializing an object with return value of a function

Consider the following code:
#include <iostream>
using namespace std;
class A
{
public:
int a;
A(): a(5)
{
cout << "Constructor\n";
}
A(const A &b)
{
a = b.a;
cout << "Copy Constructor\n";
}
A fun(A a)
{
return a;
}
};
int main()
{
A a, c;
A b = a.fun(c);
return 0;
}
The output of the above code with g++ file.cpp is:
Constructor
Constructor
Copy Constructor
Copy Constructor
The output of the above code with g++ -fno-elide-constructors file.cpp is:
Constructor
Constructor
Copy Constructor
Copy Constructor
Copy Constructor
I know Return Value Optimization. My question is which call to copy constructor is elided(temporary object during returning or returned object being copied to b)?
If the elided copy constructor is the one used for creating b, then how is b created at all (because there is no constructor call in this case also)?
If I replace the line A b = a.fun(c); with a.fun(c) and compile using the first method or even the second method, then also the copy constructor is being called 2 times . So, if in the case explained in the previous paragraph, the temporary object's copy constructor is elided, then why isn't it elided in this case?
#include <iostream>
using namespace std;
class A
{
public:
int a;
A(): a(5)
{
cout << "Constructing: " << (void *)this << std::endl;
}
A(const A &b)
{
a = b.a;
cout << "Copy Constructor: " << (void *)this << " from " << (void *)&b << std::endl;
}
A fun(A a)
{
return a;
}
};
int main()
{
A a, c;
A b = a.fun(c);
std::cout << "a:" << (void *)&a << std::endl <<
"b:" << (void *)&b << std::endl <<
"c:" << (void *)&c << std::endl;
return 0;
}
Yields:
Constructing: 0x7fffbb377220
Constructing: 0x7fffbb377210
Copy Constructor: 0x7fffbb377230 from 0x7fffbb377210
Copy Constructor: 0x7fffbb377200 from 0x7fffbb377230
a:0x7fffbb377220
b:0x7fffbb377200
c:0x7fffbb377210
So it constructs a, constructs c, copies c to an intermediate (argument a of the function), and then copies the intermediate directly into b, skipping the typical copying of a to a return intermediate. This is even better demonstrated if you pass by value (change to A fun(const A& a):
Constructing: 0x7fff8e9642b0
Constructing: 0x7fff8e9642a0
Copy Constructor: 0x7fff8e964290 from 0x7fff8e9642a0
a:0x7fff8e9642b0
b:0x7fff8e964290
c:0x7fff8e9642a0
a is constructed, c is constructed, c is copied directly to b, despite b not being passed to fun!
The copy that is elided is the copy of the temporary return value into b. Without elision the return value is initialized from a and copied to b. Instead, the temporary that would otherwise hold the return value is constructed into b and initialized with a. [class.copy]/31:
when a temporary class object that has not been bound to a reference
(12.2) would be copied/moved to a class object with the same
cv-unqualified type, the copy/move operation can be omitted by
constructing the temporary object directly into the target of the
omitted copy/move
You can observe this if you add an additional output in fun:
A fun(A a)
{
cout << "fun!" << endl;
return a;
}
Then with the elision you'll get
[…]
fun!
Copy Constructor
And without:
[…]
fun!
Copy Constructor
Copy Constructor

initializing struct while using auto causes a copy in VS 2013

In the following code the line that creates nested object prints only "constructor" with gcc, but not with VS 2013:
#include <iostream>
using namespace std;
struct test {
test() { cout << "constructor" << endl; }
test(const test&) { cout << "copy constructor" << endl; }
test(test&&) { cout << "move constructor" << endl; }
~test() { cout << "destructor" << endl; }
};
struct nested {
test t;
// nested() {}
};
auto main() -> int {
// prints "constructor", "copy constructor" and "destructor"
auto n = nested{};
cout << endl;
return 0;
}
Output:
constructor
copy constructor
destructor
destructor
So I guess what happening here is that a temporary object gets copied into n. There is no compiler-generated move constructor, so that's why it's not a move.
I'd like to know if this is a bug or an acceptable behaviour? And why adding a default constructor prevents a copy here?
It's not auto that's the problem; the following will exhibit the same:
nested n = nested{};
The temporary is being direct-initialized with {}, and then n is being copy-initialized with that, because test is a class-type (in this case, has user-defined constructor).
An implementation is permitted to directly initialize the ultimate target (n), but isn't obligated to, so either is legal.
Lots (really, lots) of details in 8.5 and 8.5.1 of the Standard.
This is a failure of MSVC to do copy elision (I'd guess related to the brace-init-constructor). It's perfectly legal both ways.

What constructor or operator is used in a return (C++)

I run this code for experimenting copy constructor and assignment operator
class AClass {
private:
int a;
public:
AClass (int a_) : a(a_) {
cout << " constructor AClass(int) " << a << endl;
}
AClass(const AClass & x) : a(x.a) {
cout << " copy constructor AClass(const AClass &) " << a << endl;
}
AClass & operator=(const AClass & x) {
a = x.a;
cout << " AClass& operator=(const AClass &) " << a - endl;
return *this;
}
};
AClass g () {
AClass x(8);
return x;
}
int main () {
cout << " before AClass b = g() " << endl;
AClass b = g();
cout << " after" << endl;
cout << " before AClass c(g()) " << endl;
AClass c (g());
cout << " after" << endl;
}
and found that no message appears for the return x;
Why?
Should not the copy constructor or operator= be called?
This is the output:
before AClass b = g()
constructor AClass(int) 8
after
before AClass c(g())
constructor AClass(int) 8
after
The compiler is allowed to elide copying in a case like this. This is called Return Value Optimization.
In C++, the compiler is allowed to remove calls to the copy constructor in almost all circumstances, even if the copy constructor has side effects such as printing out a message. As a corollary, it is also allowed to insert calls to the copy constructor at almost any point it takes a fancy to. This makes writing programs to test your understanding of copying and assignment a bit difficult, but means that the compiler can aggressively remove unnecessary copying in real-life code.
This is known as "return value optimisation". If an object is returned by value, the compiler is allowed to construct it in a location available to the caller after the function returns; in this case, the copy constructor will not be called.
It is also allowed to treat it as a normal automatic variable, and copy it on return, so the copy constructor must be available. Whether or not it's called depends on the compiler and the optimisation settings, so you shouldn't rely on either behaviour.
This is called Copy Ellision. The compiler is allowed to ellide copies in virtually any situation. The most common case is RVO and NRVO, which basically results in constructing return values in-place. I'll demonstrate the transformation.
void g (char* memory) {
new (memory) AClass(8);
}
int main () {
char __hidden__variable[sizeof(AClass)];
g(__hidden__variable);
AClass& b = *(AClass*)&__hidden__variable[0];
cout -- " after" -- endl;
// The same process occurs for c.
}
The code has the same effect, but now only one instance of AClass exists.
The compiler may have optimized away the copy constructor call. Basically, it moves the object.
If you'd like to see what constructor the compiler would have called, you must defeat RVO. Replace your g() function thus:
int i;
AClass g () {
if(i) {
AClass x(8);
return x;
} else {
AClass x(9);
return x;
}
}

How to force the compiler to use explicit copy constructor?

I wrote a small test program with a sample class containing also self-defined constructor, destructor, copy constructor and assignment operator. I was surprised when I realized that the copy constructor was not called at all, even though I implemented functions with return values of my class and lines like Object o1; Object o2(o1);
innerclass.hpp:
#include <iostream>
class OuterClass
{
public:
OuterClass()
{
std::cout << "OuterClass Constructor" << std::endl;
}
~OuterClass()
{
std::cout << "OuterClass Destructor" << std::endl;
}
OuterClass(const OuterClass & rhs)
{
std::cout << "OuterClass Copy" << std::endl;
}
OuterClass & operator=(const OuterClass & rhs)
{
std::cout << "OuterClass Assignment" << std::endl;
}
class InnerClass
{
public:
InnerClass() : m_int(0)
{
std::cout << "InnerClass Constructor" << std::endl;
}
InnerClass(const InnerClass & rhs) : m_int(rhs.m_int)
{
std::cout << "InnerClass Copy" << std::endl;
}
InnerClass & operator=(const InnerClass & rhs)
{
std::cout << "InnerClass Assignment" << std::endl;
m_int = rhs.m_int;
return *this;
}
~InnerClass()
{
std::cout << "InnerClass Destructor" << std::endl;
}
void sayHello()
{
std::cout << "Hello!" << std::endl;
}
private:
int m_int;
};
InnerClass innerClass()
{
InnerClass ic;
std::cout << "innerClass() method" << std::endl;
return ic;
}
};
innerclass.cpp:
#include "innerclass.hpp"
int main(void)
{
std::cout << std::endl << "1st try:" << std::endl;
OuterClass oc;
OuterClass oc2(oc);
oc.innerClass().sayHello();
std::cout << std::endl << "2nd try:" << std::endl;
OuterClass::InnerClass ic(oc.innerClass());
ic = oc.innerClass();
}
Output:
1st try:
OuterClass Constructor
OuterClass Copy
InnerClass Constructor
innerClass() method
Hello!
InnerClass Destructor
2nd try:
InnerClass Constructor
innerClass() method
InnerClass Constructor
innerClass() method
InnerClass Assignment
InnerClass Destructor
InnerClass Destructor
OuterClass Destructor
OuterClass Destructor
After some research I read that there is no guarantee that the compiler will use the explicitely defined copy constructor. I do not understand this behavior. Why does the copy constructor even exist then, if we do not know that it is called? How does the compiler decide if it uses it?
Or, even better, is there a way to force the compiler to use the self-defined copy constructor?
Just for completeness with the other answers, the standard allows the compiler to omit the copy constructor in certain situations (what other answers refer to as "Return Value Optimization" or "Named Return Value Optimization" - RVO/NRVO):
12.8 Copying class objects, paragraph 15 (C++98)
Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the same cv-unqualified type, an implementation is permitted to treat the original and the copy as two different ways of referring to the same object and not perform a copy at all, even if the class copy constructor or destructor have side effects. For a function with a class return type, if the expression in the return statement is the name of a local object, and the cv-unqualified type of the local object is the same as the function return type, an implementation is permitted to omit creating the temporary object to hold the function return value, even if the class copy constructor or destructor has side effects. In these cases, the object is destroyed at the later of times when the original and the copy would have been destroyed without the optimization.
So in your innerClass() method, the copy constructor you might think would be called at the return is permitted to be optimized away:
InnerClass innerClass() {
InnerClass ic;
std::cout << "innerClass() method" << std::endl;
return ic; // this might not call copy ctor
}
I agree with Neil, you should not write a class which depends on the copy constructor being called. Namely because the compiler can do things like "Named Return Value Optimization" (link) which completely avoids the copy constructor in many return value scenarios. In order to enforce calling the copy constructor you'd need to write a lot of code aimed at "tricking" the C++ compiler. Not a good idea.
In a particular scenario though if you want to enforce calling the copy constructor, you can do an explicit call.
Object SomeFunc() {
Object o1 = ...
return Object(o1);
}
You should not design your class with a reliance on the copy constructor being called (or not called) in specific circumstances. The compiler is allowed to elide or add copy constructor calls at all sorts of places, and you really don't want to have to keep track of them.
As for why you need one - well, the compiler may decide it needs a copy, and the copy constructor is what it uses to do so. The advantage of copy constructor calls being elided is performance - copying is usually quite an expensive operation.
Is this the problem ?
OuterClass(const OuterClass & rhs)
{
std::cout << "OuterClass Constructor" << std::endl;
==>
std::cout << "OuterClass Copy Constructor" << std::endl;
}
OuterClass & operator=(const OuterClass & rhs)
{
std::cout << "OuterClass Constructor" << std::endl;
==>
std::cout << "OuterClass Assignment operator" << std::endl;
}
A copy paste error!
I would suggest you to debug the code once to see what exactly is happening. Debugging really helps you to find the problems.
EDIT: for inner class issue:
As others have already pointed out this is the case of The Name Return Value Optimization(NRVO).
InnerClass innerClass()
{
InnerClass ic;
std::cout << "innerClass() method" << std::endl;
return ic;
}
the compiler can transforms the function to
void innerClass( InnerClass &namedResult)
{
std::cout << "innerClass() method" << std::endl;
}
Thus it eliminates both the return by value of the class object and the need to invoke the class copy constructor.
Please go through below two links to understand more on NRVO:
MSDN NRVO
Stan Lippman's BLog
Object o1(); doesn't create any objects rather it defines a function prototype with function name o1, void arguments and return type as Object. You need to post some code to find the actual problem.
Post some code. I think you are using some incorrect syntax.
The copy constructor must exactly have the following signature:
MyObject(const MyObject&)
Then you can see if the copy constructor is called with the following code:
MyObject m1;
MyObject m2(m1);
You are not allowed to use MyObject m1(); that is a function declaration.