I'm trying to write own Smart Pointers (C++11) and stacks with one problem, that can be explained by next example:
#include <iostream>
template<typename T_Type>
class TestTemplateClass {
private:
T_Type _state;
public:
TestTemplateClass() : _state() {
std::cout << "Default constructor" << std::endl;
}
TestTemplateClass(int inState) : _state(inState) {
std::cout << "State constructor" << std::endl;
}
template<typename T_OtherType>
TestTemplateClass(const TestTemplateClass<T_OtherType> &inValue) {
std::cout << "Template-copy constructor" << std::endl;
}
template<typename T_OtherType>
void operator = (const TestTemplateClass<T_OtherType> &inValue) {
std::cout << "Operator" << std::endl;
}
~TestTemplateClass() {
std::cout << "Destructor" << std::endl;
}
};
TestTemplateClass<int> createFunction() {
return TestTemplateClass<int>();
}
int main() {
TestTemplateClass<int> theReference = createFunction();
std::cout << "Finished" << std::endl;
return 0;
}
output:
Default constructor
Destructor
Destructor
Finished
Destructor
As you can see, there are to many destructors here. In my mind, it's some problem with interaction between copy elision and template-constructor, but I don't know what may be the reason of such bug. I tried to fix the problem by adding explicit copy-constructor and force compiler use my template-constructor:
// After TestTemplateClass(int inState), but it's not important
explicit TestTemplateClass(const OwnType &inValue) {
std::cout << "Copy constructor" << std::endl;
}
got next output:
Default constructor
Template-copy constructor
Destructor
Template-copy constructor
Destructor
Finished
Destructor
Here all looks good, but it doesn't look like a clean solution. Are there better alternatives?
(N)RVO can never introduce a discrepancy between the number of constructor and destructor calls. It's designed to make that principally impossible.
The problem is with your code. According to the rules of the language, a constructor template is never used to produce a copy constructor. The copy constructor is never a template, period.
So your class template does not actually declare a copy constructor, hence the compiler generates the default one (which of course doesn't print anything). If you need any special processing in the copy constructor, you must always declare it manually. A template will never be used to instantiate one.
Your experiment suggests there isn't a bug at all: the first version simply used the copy constructor which doesn't print anything, and the second version uses a different constructor instead because you effectively disabled it.
(it also looks like whatever compiler and options you're using doesn't do RVO)
Related
Here, i am getting different out on different compiler, why is that ?
On msvc compiler, there i'm getting extra destructor statement ?
Why i'm getting this behaviour ?
Am i missing something ?
i had looked many question on stackoverflow, but i can't find anything related to my problem ?
i also tried to look for duplicate, but didn't find one.
class A {
public:
A()
{
std::cout << "A::constructor" << "\n";
}
~A()
{
std::cout << "A::Destructor" << "\n";
}
int x = 0;
int y = 0;
};
class B {
public:
A member_var_1;
int member_var_2;
B()
{
std::cout << "B::constructor" << '\n';
}
B(A a, int b)
{
member_var_1 = a;
member_var_2 = b;
std::cout << "B(A, int)::constructor " << '\n';
}
~B()
{
std::cout << "B::destructor" << '\n';
}
};
int main()
{
B v1 {A(), 5};
}
GCC output:
A::consturctor // parameterized constructor first argument constructor
A::consturctor // construction of B's class member (member_var_1)
B(A, int)::consturcotr // B class parameterized constructor
A::Destructor // Destruction of argument of parameterized constructor
B::destructor // object goes out of scope, so B destructor called
A::Destructor // B's Destructor called member's destructor
MSVC output:
A::consturctor
A::consturctor
B(A, int)::consturcotr
A::Destructor
A::Destructor // what is it destroying? if i define a "class A" copy constructor, then i don't get this output.
B::destructor
A::Destructor
Since you're using C++17 and there is mandatory copy elision from C++17(&onwards), the extra destructor call must not be there.
A msvc bug has been reported as:
MSVC produces extra destructor call even with mandatory copy elision in C++17
Note that if you were to use C++11 or C++14, then it was possible to get an extra destructor call because prior to c++17 there was no mandatory copy elision and the parameter a could've been created using the copy/move constructor which means that you'll get the fourth destructor call as expected. You can confirm this by using the -fno-elide-constructors flag with other compilers. See Demo that has a contrived example of this.
B v1 {A(), 5};
In MSCV compiler, first, the construction of temporary A() is happening then it is elided to to "a" argument of parameterized constructor. that's why the extra destruction is happening for this temporary but it shouldn't be here because it is done implicitly.
So it is a bug in MSCV.
I am trying to create a wrapper function that has the exact same interface as the function that it wraps, with zero runtime cost overhead.
In the example code below, is it possible to design my_function_wrapped in a way so that it has the same interface as my_function, so that calling it with the exact same arguments as to my_function always yield the same results?
#include <iostream>
using namespace std;
struct SMyStruct
{
SMyStruct() { cout << "SMyStruct constructed" << std::endl;}
SMyStruct(SMyStruct&& Other) { cout << "SMyStruct moved" << std::endl;}
SMyStruct(const SMyStruct& Other) { cout << "SMyStruct copied" << std::endl; }
~SMyStruct() {cout << "SMyStruct destroyed" << std::endl;}
};
void my_function(SMyStruct Arg)
{
}
template<typename T>
void my_function_wrapped(T&& Arg)
{
my_function(std::forward<T>(Arg));
// Some extra logic here that doesn't use Arg
}
int main()
{
cout << "-----------------------------" << endl;
cout << "Direct call to my_function:" << endl;
cout << "-----------------------------" << endl;
my_function(SMyStruct());
cout << "-----------------------------" << endl;
cout << "Wrapped call to my_function:" << endl;
cout << "-----------------------------" << endl;
my_function_wrapped(SMyStruct());
return 0;
}
This program outputs:
-----------------------------
Direct call to my_function:
-----------------------------
SMyStruct constructed
SMyStruct destroyed
-----------------------------
Wrapped call to my_function:
-----------------------------
SMyStruct constructed
SMyStruct moved
SMyStruct destroyed
SMyStruct destroyed
I realize that copy/move is elided on the first call to my_function because SMyStruct() is a prvalue. Is it possible to wrap this call in my_function_wrapped and still get the elided copy/move? Is there any zero-cost way to abstract away the call?
godbolt-link to the code: https://godbolt.org/z/joGTTe64f
Thanks!
No, it is not possible to chain copy elision of prvalues through function calls like this.
Copy elision only works because the caller can construct the function parameter knowing where it needs to place it from the declaration of the function and the calling convention used.
The original caller doesn't know that you are going to simply forward the argument to another function in the body and therefore it cannot know that it is supposed to construct the object into the deeper stack frame. C++ is also designed in such a way that functions can be compiled individually only having to know the declarations of other functions (constant expression evaluation aside). Definitions of the functions don't even have to be available where a call happens.
Allowing this would require some additional language feature to annotate a function declaration to inform callers where they have to construct the parameter and I think it would be difficult to find a good specification for such a feature.
What you can do is pass the arguments for your constructor, or more generally a callable object which creates your prvalue, around, e.g.
template<typename F>
void my_function_wrapped(F&& f)
{
my_function(std::invoke(std::forward<F>(f)));
}
//...
my_function_wrapped([]{ return SMyStruct(); });
The lambda can capture arguments to the constructor if needed.
(Note however that all of this requires C++17. You also tagged C++14, but in C++14 there was no guaranteed copy elision in any of the situations under discussion anyway.)
It depends on your real case (or if there is a real case to begin with), though in your example there is really no point in passing the SMyStruct to the wrapper to forward it to the actual function (because SMyStruct has no state). If instead you forward parameters for the constructor you get desired output:
template<typename...T>
void my_function_wrapped(T&&... Arg)
{
my_function(SMyStruct(std::forward<T>(Arg)...));
}
Live Demo
class Entity
{
public:
int a;
Entity(int t)
:a(t)
{
std::cout << "Constructor !" << std::endl;
}
~Entity()
{
std::cout << "Destructor !" << std::endl;
}
Entity(Entity& o)
{
std::cout << "Copied !" << std::endl;
this->a = o.a;
}
};
Entity hi()
{
Entity oi(3);
return oi;
}
int main()
{
{
Entity o(1);
o = hi();
}
std::cin.get();
}
OUTPUT:
Constructor !
Constructor !
Copied !
Destructor !
Destructor !
Destructor !
I created two objects and I copied one, So three constructors and three destructors.
Your "Copied!" line in the output is coming from the copy constructor, so you're creating three objects, not just two (then you're destroying all three, as expected).
Note that a copy constructor should normally take its argument by const reference. At a guess, you may be using Microsoft's C++ compiler, which will bind a temporary to a non-const reference.
Also note that if you turn on optimization, you can probably expect to see just two constructors and two destructors, with no copy construction happening. With a new enough (C++17) compiler, that should happen even if you don't turn on optimization (copy elision has become mandatory).
This is a trivial question
Can any one explain the reason for three destructor?
when you call
o=hi();
your function is called which makes an object of type Entity , which in return calls the constructor.
This is where you get one extra constructor message
Replace your Entity(int t) contructor by this
Entity(int t)
:a(t)
{
std::cout << "Constructor created with integer "<< a << std::endl;
}
You will see which constructors were called when you run the code.
I want to know what's happening here:
class Test {
public:
Test() { std::cout << "Constructor" << std::endl; }
Test(const Test &) { std::cout << "Copy" << std::endl; }
Test(const Test &&) { std::cout << "Move" << std::endl; }
~Test() { std::cout << "Destructor" << std::endl; }
};
std::vector<Test> getTestVektor() {
std::vector<Test> TestVektor(1);
return TestVektor;
}
Test getTest() {
Test TestVariable;
return TestVariable;
}
int main() {
{
std::vector<Test> TestVektor = getTestVektor();
}
std::cout << std::endl;
{
Test TestVarible = getTest();
}
std::cout << std::endl;
{
std::vector<Test> TestVektor(1);
std::vector<Test> TestVektor2 = TestVektor;
}
return 0;
}
compiled with VisualStudio 2012:
Constructor
Destructor
Constructor
Move
Destructor
Destructor
Constructor
Copy
Destructor
Destructor
One could explain the first case with copy elision. But that's contrary to the second case, where the move constructor was called.
Another explanation would be, that the std::vector in the function releases its contents and passes it to the second std::vector, so there is no call of the copy constructor. But the third case shows, that that's not the case.
So, what's happening here? Or is this just mazy compiler opitimization?
The first case (at worst) moves the vector (so just transfers the internal pointer, without copy/move of Test).
The 3rd case makes a copy of vector, you would have to do the following to move it instead of copy:
{
std::vector<Test> TestVektor(1);
std::vector<Test> TestVektor2 = std::move(TestVektor);
}
FYI the output from clang, with -O2:
Constructor
Destructor
Constructor
Destructor
Constructor
Copy
Destructor
Destructor
Why visual studio would invoke a move in case 2 is a mystery to me. Did you disable optimisations?
One could explain the first case with copy elision.
TestVektor was move constructed from the temporary vector that was returned from getTestVektor. One, both or neither of the moves may have been elided.
But that's contrary to the second case, where the move constructor was called.
Copy/move elision is not mandatory. It could be used for both the return from getTest and copy initialization of TestVarible, but it wasn't used for one of them.
Versions of both GCC and Clang that I tested elided both.
Another explanation would be, that the std::vector in the function releases its contents and passes it to the second std::vector
That's exactly what the move constructor of std::vector does.
But the third case does copy assignment, not a move construction.
In conclusion, what's happening here is mostly explained by the move constructor of std::vector, but the second case also shows observable (lack of) side effects from copy/move elision.
I'm trying to establish whether it is safe for a C++ function to return an object that has a constructor and a destructor. My understanding of the standard is that it ought to be possible, but my tests with simple examples show that it can be problematic. For example the following program:
#include <iostream>
using namespace std;
struct My
{ My() { cout << "My constructor " << endl; }
~My() { cout << "My destructor " << endl; }
};
My function() { My my; cout << "My function" << endl; return my; }
int main()
{ My my = function();
return 0;
}
gives the output:
My constructor
My function
My destructor
My destructor
when compiled on MSVC++, but when compiled with gcc gives the following output:
My constructor
My function
My destructor
Is this a case of "undefined behavior", or is one of the compilers not behaving in a standard way? If the latter, which ? The gcc output is closer to what I would have expected.
To date, I have been designing my classes on the assumption that for each constructor call there will be at most one destructor call, but this example seems to show that this assumption does not always hold, and can be compiler-dependent. Is there anything in the standard that specifies what should happen here, or is it better to avoid having functions return non-trivial objects ? Apologies if this question is a duplicate.
In both cases, the compiler generates a copy constructor for you, that has no output so you won't know if it is called: See this question.
In the first case the compiler generated copy constructor is used, which matches the second destructor call. The line return my; calls the copy constructor, giving it the variable my to be used to construct the return value. This doesn't generate any output.
my is then destroyed. Once the function call has completed, the return value is destroyed at the end of the line { function();.
In the second case, the copy for the return is elided completely (the compiler is allowed to do this as an optimisation). You only ever have one My instance. (Yes, it is allowed to do this even though it changes the observable behaviour of your program!)
These are both ok. Although as a general rule, if you define your own constructor and destructor, you should also define your own copy constructor (and assignment operator, and possibly move constructor and move assignment if you have c++11).
Try adding your own copy constructor and see what you get. Something like
My (const My& otherMy) { cout << "My copy constructor\n"; }
The problem is that your class My violates the Rule of Three; if you write a custom destructor then you should also write a custom copy constructor (and copy assignment operator, but that's not relevant here).
With:
struct My
{ My() { cout << "My constructor " << endl; }
My(const My &) { cout << "My copy constructor " << endl; }
~My() { cout << "My destructor " << endl; }
};
the output for MSVC is:
My constructor
My function
My copy constructor
My destructor
My destructor
As you can see, (copy) constructors match with destructors correctly.
The output under gcc is unchanged, because gcc is performing copy elision as allowed (but not required) by the standard.
You are missing two things here: the copy constructor and NRVO.
The behavior seen with MSVC++ is the "normal" behavior; my is created and the rest of the function is run; then, when returning, a copy of your object is created. The local my object is destroyed, and the copy is returned to the caller, which just discards it, resulting in its destruction.
Why does it seem that you are missing a constructor call? Because the compiler automatically generated a copy constructor, which is called but doesn't print anything. If you added your own copy constructor:
My(const My& Right) { cout << "My copy constructor " << endl; }
you'd see
My constructor <----+
My function | this is the local "my" object
My copy constructor <--|--+
My destructor <----+ | this is the return value
My destructor <-----+
So the point is: it's not that there are more calls to destructors than constructors, it's just that you are not seeing the call to the copy constructor.
In the gcc output, you are also seeing NRVO applied.
NRVO (Named Return Value Optimization) is one of the few cases where the compiler is allowed to perform an optimization that alters the visible behavior of your program. In fact, the compiler is allowed to elide the copy to the temporary return value, and construct the returned object directly, thus eliding temporary copies.
So, no copy is created, and my is actually the same object that is returned.
My constructor <-- called at the beginning of f
My function
My destructor <-- called after f is terminated, since
the caller discarded the return value of f
To date, I have been designing my classes on the assumption that for each constructor call there will be at most one destructor call [...]
You can still "assume" that since it is true. Each constructor call will go in hand with exactly one destructor call. (Remember that if you handle stuff on the free/heap memory on your own.)
[..] and can be compiler-dependent [...]
In this case it can't. It is optimization depedant. Both, MSVC and GCC behave identically if optimization is applied.
Why don't you see identical behaviour?
1. You don't track everything that happens with your object. Compiler-generated functions bypass your output.
If you want to "follow-up" on the things your compiler does with your objects, you should define all of the special members so you can really track everything and do not get bypassed by any implicit function.
struct My
{
My() { cout << "My constructor " << endl; }
My(My const&) { cout << "My copy-constructor " << endl; }
My(My &&) { cout << "My move-constructor " << endl; }
My& operator=(My const&) { cout << "My copy-assignment " << endl; }
My& operator=(My &&) { cout << "My move-assignment " << endl; }
~My() { cout << "My destructor " << endl; }
};
[Note: The move-constructor and move-assignment will not be implicitly present if you have the copy ones but it's still nice to see when the compiler use which of them.]
2. You don't compile with optimization on both MSVC and GCC.
If compiled with MSVC++11 /O2 option the output is:
My constructor
My function
My destructor
If compiled in debug mode / without optimization:
My constructor
My function
My move-constructor
My destructor
My destructor
I can't do a test on gcc to verify if there's an option that enforces all of these steps but -O0 should do the trick I guess.
What's the difference between optimized and non-optimized compilation here?
The case without any copy omittance:
The completely "non-optimized" behaviour in this line My my_in_main = function();
(changed the name to make things clear) would be:
Call function()
In function construct My My my;
Output stuff.
Copy-construct my into the return value instance.
return and destroy my instance.
Copy(or move in my example)-construct the return value instance into my_in_main.
Destroy the return value instance.
As you can see: we have at most two copies (or one copy and one move) here but the compilers may possibly omit them.
To my understanding, the first copy is omited even without optimization turned on (in this case), leaving the process as follows:
Call function()
In function construct My My my; First constructor output!
Output stuff. Function output!
Copy(or move in my example)-construct the return value instance into my_in_main. Move output!
Destroy the return value instance. Destroy output!
The my_in_main is destroy at the end of main giving the last Destroy output!. So we know what happens in the non-optimized case now.
Copy elision
The copy (or move if the class has a move constructor as in my example) can be elided.
§ 12.8 [class.copy] / 31
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.
So now the question is when does this happen in this example? The reason for the elison of the first copy is given in the very same paragraph:
[...] in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cvunqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value.
Return type matches type in the return statement: function will construct My my; directly into the return value.
The reason for the elison of the second copy/move:
[...] 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.
Target type matches the type returned by the function: The return value of the function will be constructed into my_in_main.
So you have a cascade here:
My my; in your function is directly constructed into the return value which is directly constructed into my_in_main So you have in fact only one object here and function() would (whatever it does) in fact operate on the object my_in_main.
Call function()
In function construct My instance into my_in_main. Constructor output!
Output stuff. Function output!
my_in_main is still destroyed at the end of main giving a Destructor output!.
That makes three outputs in total: Those you observe if optimization is turned on.
An example where elision is not possible.
In the following example both copies mentioned above cannot be omitted because the class types do not match:
The return statement does not match the return type
The target type does not match the return type of the function
I just created two additional types:
#include <iostream>
using namespace std;
struct A
{
A(void) { cout << "A constructor " << endl; }
~A(void) { cout << "A destructor " << endl; }
};
struct B
{
B(A const&) { cout << "B copy from A" << endl; }
~B(void) { cout << "B destructor " << endl; }
};
struct C
{
C(B const &) { cout << "C copy from B" << endl; }
~C(void) { cout << "C destructor " << endl; }
};
B function() { A my; cout << "function" << endl; return my; }
int main()
{
C my_in_main(function());
return 0;
}
Here we have the "completely non-optimized behaviour" I mentioned above. I'll refer to the points I've drawn there.
A constructor (see 2.)
function (see 3.)
B copy from A (see 4.)
A destructor (see 5.)
C copy from B (see 6.)
B destructor (see 7.)
C destructor (instance in main, destroy at end of main)