C++ constructor: garbage while initialization of const reference - c++

what is wrong with this code, why do I get wrong answer:
class X
{
private:
const int a;
const int& b;
public:
X(): a(10) , b(20)
{
// std::cout << "constructor : a " << a << std::endl;
// std::cout << "constructor : b " << b << std::endl;
}
void display()
{
std::cout << "display():a:" << a << std::endl;
std::cout << "display():b:" << b << std::endl;
}
};
int
main(void)
{
X x;
x.display();
return 0;
}
The above code will give me the result as
display():a:10
display():b:1104441332
But If I remove the commented 2 lines inside the default constructor it gives me proper result which is
constructor : a 10
constructor : b 20
display():a:10
display():b:20
please help, Thank you

You are initializing b as a reference to a temporary.
The value 20 is created and exists only for the scope of the constructor.
The behavior of the code after this is very interesting - on my machine, I get different values from the ones you posted, but the fundamental behavior is still nondeterministic.
This is because when the value to which the reference points falls out of scope, it begins to reference garbage memory instead, giving unpredictable behavior.
See Does a const reference prolong the life of a temporary?; the answer https://stackoverflow.com/a/2784304/383402 links to the relevant section of the C++ standard, specifically the below text:
A temporary bound to a reference member in a constructor’s ctor-initializer
(12.6.2) persists until the constructor exits.
This is why you always get the right value in the print within the constructor, and rarely (but possibly sometimes!) after. When the constructor exits, the reference dangles and all bets are off.

I'll let my compiler answer this one:
$ g++ -std=c++98 -Wall -Wextra -pedantic test.cpp
test.cpp: In constructor 'X::X()':
test.cpp:9:26: warning: a temporary bound to 'X::b' only persists until the constructor exits [-Wextra]
$
You should turn on the warnings on your compiler as well.

b refers to a temporary. What you have read (when printing) is an invalid location by the time it is read since the temporary 20 has technically gone out of scope.
To explain inconsistent results:
It is undefined behavior. What you see may be different if you:
change your compiler
change your compiler settings
build for another architecture
change your class' member layout
add or remove things from the memory region near the instance of x
etc.
You should always always avoid undefined behavior.
But why would the value change? Your reference likely refers to a stack address which has been rewritten (e.g. reused) by the time it's printed.

You're binding the const& to a temporary, which doesn't live beyond the call to the constructor. The C++03 standard specfically says "a temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits" (12.2/5 "Temporary objects").
So your code has undefined behavior - you might get nonsense, or something that appears to be 'working'.
FWIW, MSVC 2010 gives the following warning on that code:
C:\temp\test.cpp(12) : warning C4413: 'X::b' : reference member is initialized to a temporary that doesn't persist after the constructor exits

Related

What is expected lifetime of std::intializer_list object in C++14?

Please consider this simplified c++14 program:
#include <iostream>
struct A
{
A() { std::cout << "A() "; }
~A() { std::cout << "~A() "; }
};
int main()
{
auto l = std::initializer_list<A>{A()};
std::cout << ". ";
}
https://gcc.godbolt.org/z/1GWvGfxne
GCC prints here
A() . ~A()
Meaning that std::initializer_list is destructed at the end of scope.
Clang prints:
A() ~A() .
Destroying std::initializer_list in the line where it is constructed.
Are both compiler behave correctly here or one of them is wrong?
It's subtle.
A std::initializer_list is backed by an underlying array (produced by the compiler). This array is a like a temporary object, and the std::initializer_list is a sort of reference type that binds to it. So it will extend the temporary array's lifetime so long as the "reference" exist.
In C++14, we do not have guaranteed copy elision. So what should happen is as though std::initializer_list<A>{A()} produced a temporary initializer_list, bound another temporary array to it, and copied the temporary initializer_list to l.
std::initializer_list behaves like a regular reference, as far as lifetime extension is concerned. Only the original reference extends the lifetime, and our original is temporary itself. So the underlying array goes out of existence at the end of the full expression containing the initialization of l. Clang is the correct one.
Direct-initialization ...
std::initializer_list<A> l {A()};
... produces the same output on both compilers.
Meanwhile, your original code behaves the same on GCC and Clang when compiling for C++17.
According to cppreference:
Until the resolution of CWG issue 1696, a temporary is permitted to
bound to a reference member in a constructor initializer list, and it
persists only until the constructor exits, not as long as the object
exists. Such initialization is ill-formed since CWG 1696, although
many compilers still support it (a notable exception is clang).

Why can we use an object during its declaration? [duplicate]

I am surprised to accidentally discover that the following works:
#include <iostream>
int main(int argc, char** argv)
{
struct Foo {
Foo(Foo& bar) {
std::cout << &bar << std::endl;
}
};
Foo foo(foo); // I can't believe this works...
std::cout << &foo << std::endl; // but it does...
}
I am passing the address of the constructed object into its own constructor. This looks like a circular definition at the source level. Do the standards really allow you to pass an object into a function before the object is even constructed or is this undefined behavior?
I suppose it's not that odd given that all class member functions already have a pointer to the data for their class instance as an implicit parameter. And the layout of the data members is fixed at compile time.
Note, I'm NOT asking if this is useful or a good idea; I'm just tinkering around to learn more about classes.
This is not undefined behavior. Although foo is uninitialized, you are using it a way that is allowed by the standard. After space is allocated for an object but before it is fully initialized, you are allowed to use it limited ways. Both binding a reference to that variable and taking its address are allowed.
This is covered by defect report 363: Initialization of class from self which says:
And if so, what is the semantics of the self-initialization of UDT?
For example
#include <stdio.h>
struct A {
A() { printf("A::A() %p\n", this); }
A(const A& a) { printf("A::A(const A&) %p %p\n", this, &a); }
~A() { printf("A::~A() %p\n", this); }
};
int main()
{
A a=a;
}
can be compiled and prints:
A::A(const A&) 0253FDD8 0253FDD8
A::~A() 0253FDD8
and the resolution was:
3.8 [basic.life] paragraph 6 indicates that the references here are valid. It's permitted to take the address of a class object before it is fully initialized, and it's permitted to pass it as an argument to a reference parameter as long as the reference can bind directly. Except for the failure to cast the pointers to void * for the %p in the printfs, these examples are standard-conforming.
The full quote of section 3.8 [basic.life] from the draft C++14 standard is as follows:
Similarly, before the lifetime of an object has started but after the
storage which the object will occupy has been allocated or, after the
lifetime of an object has ended and before the storage which the
object occupied is reused or released, any glvalue that refers to the
original object may be used but only in limited ways. For an object
under construction or destruction, see 12.7. Otherwise, such a glvalue
refers to allocated storage (3.7.4.2), and using the properties of the
glvalue that do not depend on its value is well-defined. The program
has undefined behavior if:
an lvalue-to-rvalue conversion (4.1) is applied to such a glvalue,
the glvalue is used to access a non-static data member or call a non-static member function of the
object, or
the glvalue is bound to a reference to a virtual base class (8.5.3), or
the glvalue is used as the operand of a dynamic_cast (5.2.7) or as the operand of typeid.
We are not doing anything with foo that falls under undefined behavior as defined by the bullets above.
If we try this with Clang, we see an ominous warning (see it live):
warning: variable 'foo' is uninitialized when used within its own initialization [-Wuninitialized]
It is a valid warning since producing an indeterminate value from an uninitialized automatic variable is undefined behavior. However, in this case you are just binding a reference and taking the address of the variable within the constructor, which does not produce an indeterminate value and is valid. On the other hand, the following self-initialization example from the draft C++11 standard:
int x = x ;
does invoke undefined behavior.
Active issue 453: References may only bind to “valid” objects also seems relevant but is still open. The initial proposed language is consistent with Defect Report 363.
The constructor is called at a point where memory is allocated for the object-to-be. At that point, no object exists at that location (or possibly an object with a trivial destructor). Furthermore, the this pointer refers to that memory and the memory is properly aligned.
Since it's allocated and aligned memory, we may refer to it using lvalue expressions of Foo type (i.e. Foo&). What we may not yet do is have an lvalue-to-rvalue conversion. That's only allowed after the constructor body is entered.
In this case, the code just tries to print &bar inside the constructor body. It would even be legal to print bar.member here. Since the constructor body has been entered, a Foo object exists and its members may be read.
This leaves us with one small detail, and that's name lookup. In Foo foo(foo), the first foo introduces the name in scope and the second foo therefore refers back to the just-declared name. That's why int x = x is invalid, but int x = sizeof(x) is valid.
As said in other answers, an object can be initialized with itself as long as you do not use its values before they are initialized. You can still bind the object to a reference or take its address.
But beyond the fact that it is valid, let's explore a usage example.
The example below might be controversial, you can surely propose many other ideas for implementing it. And yet, it presents a valid usage of this strange C++ property, that you can pass an object into its own constructor.
class Employee {
string name;
// manager may change so we don't hold it as a reference
const Employee* pManager;
public:
// we prefer to get the manager as a reference and not as a pointer
Employee(std::string name, const Employee& manager)
: name(std::move(name)), pManager(&manager) {}
void modifyManager(const Employee& manager) {
// TODO: check for recursive connection and throw an exception
pManager = &manager;
}
friend std::ostream& operator<<(std::ostream& out, const Employee& e) {
out << e.name << " reporting to: ";
if(e.pManager == &e)
out << "self";
else
out << *e.pManager;
return out;
}
};
Now comes the usage of initializing an object with itself:
// it is valid to create an employee who manages itself
Employee jane("Jane", jane);
In fact, with the given implementation of class Employee, the user has no other choice but to initialize the first Employee ever created, with itself as its own manager, as there is no other Employee yet that can be passed. And in a way that makes sense, as the first employee created should manage itself.
Code: http://coliru.stacked-crooked.com/a/9c397bce622eeacd

C++11 scoping and lifetime of temporary bound to a (const) reference (GCC)

I have the following questions related to the same situation (not in general):
Why does the compiler not produce a warning when a temporary is bound
to a reference?
How does lifetime extension of a temporary work (when it is bound to
a reference)?
How to interpret / understand the C++ standard (C++11)?
Is this a bug (in the compiler)? Should it be?
So this is what we are talking about:
struct TestRefInt {
TestRefInt(const int& a) : a_(a) {};
void DoSomething() { cout << "int:" << a_ << endl; }
protected:
const int& a_;
};
Should TestRefInt tfi(55); and tfi.DoSomething(); work? How and where?
So here is a code
TestRefInt tfi(55);
int main() {
TestRefInt ltfi(8);
tfi.DoSomething();
ltfi.DoSomething();
return 0;
}
What should this do?
Here I will elaborate some more.
Consider this real world (simplified) example. How does it look like to a novice/beginner C++ programmer? Does this make sense?
(you can skip the code the issue is the same as above)
#include <iostream>
using namespace std;
class TestPin //: private NonCopyable
{
public:
constexpr TestPin(int pin) : pin_(pin) {}
inline void Flip() const {
cout << " I'm flipping out man : " << pin_ << endl;
}
protected:
const int pin_;
};
class TestRef {
public:
TestRef(const TestPin& a) : a_(a) {};
void DoSomething() { a_.Flip(); }
protected:
const TestPin& a_;
};
TestRef g_tf(1);
int main() {
TestRef tf(2);
g_tf.DoSomething();
tf.DoSomething();
return 0;
}
Command line:
/** Compile:
Info: Internal Builder is used for build
g++ -std=c++11 -O0 -g3 -Wall -Wextra -Wconversion -c -fmessage-length=0 -o "src\\Scoping.o" "..\\src\\Scoping.cpp"
g++ -o Scoping.exe "src\\Scoping.o"
13:21:39 Build Finished (took 346ms)
*/
Output:
/**
I'm flipping out man : 2293248
I'm flipping out man : 2
*/
The issue:
TestRef g_tf(1); /// shouldn't the reference to temporary extend it's life in global scope too?
What does the standard says?
From How would auto&& extend the life-time of the temporary object?
Normally, a temporary object lasts only until the end of the full
expression in which it appears. However, C++ deliberately specifies
that binding a temporary object to a reference to const on the stack
lengthens the lifetime of the temporary to the lifetime of the
reference itself
^^^^^
Globals are not allocated on stack, so lifetime is not extended. However, the compiler does not produce any warning message whatsoever! Shouldn’t it at least do that?
But my main point is: from a usability standpoint (meaning as the user of C++, GCC as a programmer) it would be useful if the same principle would be extended to not just stack, but to global scope, extending the lifetime (making global temporaries “permanent”).
Sidenote:
The problem is further complicated by the fact that the TestRef g_tf(1); is really TestRef g_tf{ TestPin{1} }; but the temporary object is not visible in the code, and without looking at the constructor declaration it looks like the constructor is called by an integer, and that rarely produces this kind of error.
As far as I know the only way to fix the problem is to disallow temporaries in initialization by deleting TestRefInt(const int&& a) =delete; constructor. But this also disallows it on stack, where lifetime extension worked.
But the previous quote is not exactly what the C++11 standard say. The relevant parts of the C++11 Standard are 12.2 p4 and p5:
4 - There are two contexts in which temporaries are destroyed at a
different point than the end of the full expression. The first context
is [...]
5 - The second context is when a reference is bound to a
temporary. The temporary to which the reference is bound or the
temporary that is the complete object of a subobject to which the
reference is bound persists for the lifetime of the reference except:
— A temporary bound to a reference member in a constructor’s
ctor-initializer (12.6.2) persists until the constructor exits.
— A temporary bound to a reference parameter in a function call (5.2.2)
persists until the completion of the full-expression containing the
call. § 12.2 245 c ISO/IEC N3337
— The lifetime of a temporary bound
to the returned value in a function return statement (6.6.3) is not
extended; the temporary is destroyed at the end of the full-expression
in the return statement.
— A temporary bound to a reference in a
new-initializer (5.3.4) persists until the completion of the
full-expression containing the new-initializer. [Example: struct S {
int mi; const std::pair& mp; }; S a { 1, {2,3} }; S* p = new S{ 1,
{2,3} }; // Creates dangling reference — end example ] [ Note: This
may introduce a dangling reference, and implementations are encouraged
to issue a warning in such a case. — end note ]
My English and understanding of the standard is not good enough, so what exception is this?
The “— A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.” or “reference parameter in a function call” does not mention anything about allocation on stack or in global scope. The other exceptions do not seem to apply. Am I wrong?
Which one is this, or none of them?
We have a temporary in a function call (the constructor) and then a reference to
the temporary is bound to a member reference in the initializer. Is this undefined behavior? Or the exception still applies, and the temporary should be destroyed? (or both)
What about this?
struct TestRefIntDirect {
TestRefIntDirect(int a) : a_(a) {};
void DoSomething() { cout << "int:" << a_ << endl; }
protected:
const int& a_;
};
One less reference, same behavior.
Why does it work in one case (instantiation inside a function) versus in other case (in global scope)?
Does GCC not “destroy” one of them by “accident”?
My understanding is that none of them should work, the temporary should not persist as the standard says. It seems GCC just "lets" you access not persisting objects (sometimes). I guess that the standard does not specify what the compiler should warn about, but can we agree that it should? (in other cases it does warn about ‘returning reference to temporary’) I think it should here too.
Is this a bug or maybe there should be a feature request somewhere?
It seems to me like GCC says “Well, you shouldn’t touch this cookie, but I will leave it here for you and not warn anyone about it.” ...which I don’t like.
This thing others reference about stack I did not find in the standard, where is it coming from? Is this misinformation about the standard? Or is this a consequence of something in the standard? (Or is this just implementation coincidence, that the temporary is not overwritten and can be referenced, because it happened to be on the stack? Or is this compiler defined behavior, extension?)
The more I know C++ the more it seems that every day it is handing me a gun to shoot myself in the foot with it…
I would like to be warned by the compiler if I’m doing something wrong, so I can fix it. Is that too much to ask?
Other related posts:
Temporary lifetime extension
C++: constant reference to temporary
Does a const reference prolong the life of a temporary?
Returning temporary object and binding to const reference
I didn’t want to write this much. If you read it all, thanks.

Is passing a C++ object into its own constructor legal?

I am surprised to accidentally discover that the following works:
#include <iostream>
int main(int argc, char** argv)
{
struct Foo {
Foo(Foo& bar) {
std::cout << &bar << std::endl;
}
};
Foo foo(foo); // I can't believe this works...
std::cout << &foo << std::endl; // but it does...
}
I am passing the address of the constructed object into its own constructor. This looks like a circular definition at the source level. Do the standards really allow you to pass an object into a function before the object is even constructed or is this undefined behavior?
I suppose it's not that odd given that all class member functions already have a pointer to the data for their class instance as an implicit parameter. And the layout of the data members is fixed at compile time.
Note, I'm NOT asking if this is useful or a good idea; I'm just tinkering around to learn more about classes.
This is not undefined behavior. Although foo is uninitialized, you are using it a way that is allowed by the standard. After space is allocated for an object but before it is fully initialized, you are allowed to use it limited ways. Both binding a reference to that variable and taking its address are allowed.
This is covered by defect report 363: Initialization of class from self which says:
And if so, what is the semantics of the self-initialization of UDT?
For example
#include <stdio.h>
struct A {
A() { printf("A::A() %p\n", this); }
A(const A& a) { printf("A::A(const A&) %p %p\n", this, &a); }
~A() { printf("A::~A() %p\n", this); }
};
int main()
{
A a=a;
}
can be compiled and prints:
A::A(const A&) 0253FDD8 0253FDD8
A::~A() 0253FDD8
and the resolution was:
3.8 [basic.life] paragraph 6 indicates that the references here are valid. It's permitted to take the address of a class object before it is fully initialized, and it's permitted to pass it as an argument to a reference parameter as long as the reference can bind directly. Except for the failure to cast the pointers to void * for the %p in the printfs, these examples are standard-conforming.
The full quote of section 3.8 [basic.life] from the draft C++14 standard is as follows:
Similarly, before the lifetime of an object has started but after the
storage which the object will occupy has been allocated or, after the
lifetime of an object has ended and before the storage which the
object occupied is reused or released, any glvalue that refers to the
original object may be used but only in limited ways. For an object
under construction or destruction, see 12.7. Otherwise, such a glvalue
refers to allocated storage (3.7.4.2), and using the properties of the
glvalue that do not depend on its value is well-defined. The program
has undefined behavior if:
an lvalue-to-rvalue conversion (4.1) is applied to such a glvalue,
the glvalue is used to access a non-static data member or call a non-static member function of the
object, or
the glvalue is bound to a reference to a virtual base class (8.5.3), or
the glvalue is used as the operand of a dynamic_cast (5.2.7) or as the operand of typeid.
We are not doing anything with foo that falls under undefined behavior as defined by the bullets above.
If we try this with Clang, we see an ominous warning (see it live):
warning: variable 'foo' is uninitialized when used within its own initialization [-Wuninitialized]
It is a valid warning since producing an indeterminate value from an uninitialized automatic variable is undefined behavior. However, in this case you are just binding a reference and taking the address of the variable within the constructor, which does not produce an indeterminate value and is valid. On the other hand, the following self-initialization example from the draft C++11 standard:
int x = x ;
does invoke undefined behavior.
Active issue 453: References may only bind to “valid” objects also seems relevant but is still open. The initial proposed language is consistent with Defect Report 363.
The constructor is called at a point where memory is allocated for the object-to-be. At that point, no object exists at that location (or possibly an object with a trivial destructor). Furthermore, the this pointer refers to that memory and the memory is properly aligned.
Since it's allocated and aligned memory, we may refer to it using lvalue expressions of Foo type (i.e. Foo&). What we may not yet do is have an lvalue-to-rvalue conversion. That's only allowed after the constructor body is entered.
In this case, the code just tries to print &bar inside the constructor body. It would even be legal to print bar.member here. Since the constructor body has been entered, a Foo object exists and its members may be read.
This leaves us with one small detail, and that's name lookup. In Foo foo(foo), the first foo introduces the name in scope and the second foo therefore refers back to the just-declared name. That's why int x = x is invalid, but int x = sizeof(x) is valid.
As said in other answers, an object can be initialized with itself as long as you do not use its values before they are initialized. You can still bind the object to a reference or take its address.
But beyond the fact that it is valid, let's explore a usage example.
The example below might be controversial, you can surely propose many other ideas for implementing it. And yet, it presents a valid usage of this strange C++ property, that you can pass an object into its own constructor.
class Employee {
string name;
// manager may change so we don't hold it as a reference
const Employee* pManager;
public:
// we prefer to get the manager as a reference and not as a pointer
Employee(std::string name, const Employee& manager)
: name(std::move(name)), pManager(&manager) {}
void modifyManager(const Employee& manager) {
// TODO: check for recursive connection and throw an exception
pManager = &manager;
}
friend std::ostream& operator<<(std::ostream& out, const Employee& e) {
out << e.name << " reporting to: ";
if(e.pManager == &e)
out << "self";
else
out << *e.pManager;
return out;
}
};
Now comes the usage of initializing an object with itself:
// it is valid to create an employee who manages itself
Employee jane("Jane", jane);
In fact, with the given implementation of class Employee, the user has no other choice but to initialize the first Employee ever created, with itself as its own manager, as there is no other Employee yet that can be passed. And in a way that makes sense, as the first employee created should manage itself.
Code: http://coliru.stacked-crooked.com/a/9c397bce622eeacd

Temporary is still binded to reference, when casted to reference type first

When compiling some weird code for better C++ standard understanding, I met an example, where I'm not actually sure what is happening. Consider a simple class, which make debug output, when it constructed or destructed:
struct C {
C() { cout << "Constructed\t" << this << "\n"; }
C(const C& source) = delete;
C(C&&) = delete;
~C() { cout << "Destructed\t" << this << "\n"; }
};
Now the code, which behaviour I don't understand:
int main()
{
const C& r = static_cast<const C&>(C());
cout << "Next line" << endl;
}
The output is (tried it with gcc and clang):
Constructed 0x7fff6d6ebe60
Next line
Destructed 0x7fff6d6ebe60
So, as u can see here, temporary object is binded to reference even when it casted to reference type first. I'm not sure why this is happening. I've tried to answer it myself and this is my thoughts:
C() creates a temporary prvalue
For static_cast 5.2.9p4 is applicated:
Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.
So a temporary reference is created and the result of static_cast expression is lvalue
What happens next and why lifetime of temporary is extended? Is it something like a temporary binded to temporary reference, which itself binded to other reference?
P.S. Also tried this (add an address-taking and derefernce operators):
int main()
{
const C& r = *&static_cast<const C&>(C());
cout << "Next line" << endl;
}
And gcc output is still:
Constructed 0x7fffa1c50157
Next line
Destructed 0x7fffa1c50157
while clang destroy temporary before "Next line" in this case:
Constructed 0x7fff3374ab60
Destructed 0x7fff3374ab60
Next line
Try to look at clauses 12.2/4 and 12.2/5 of Standard:
There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called to initialize an element of an array. If
the constructor has one or more default arguments, the destruction of every temporary created in a default
argument is sequenced before the construction of the next array element, if any.
The second context is when a reference is bound to a temporary. The temporary to which the reference is
bound or the temporary that is the complete object of a subobject to which the reference is bound persists
for the lifetime of the reference except: ...
this should answer your question - why the lifetime is extended.