binding a temporary object to a const reference [duplicate] - c++

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Why not non-const reference to temporary objects? [duplicate]
(4 answers)
Closed 4 years ago.
#include <iostream>
using namespace std;
int f()
{
int x=1;
return x;
}
int main()
{
const int& s = f();
cout << s << endl;
}
#include <iostream>
using namespace std;
int x=1;
int &f()
{
return x;
}
int main()
{
const int& s = f();
cout << s << endl;
}
Both of these programs are correct. But when I use
int &f()
{
int x=1;
return x;
}
instead of
int f()
{
int x=1;
return x;
}
I get an error:
main.cpp: In function 'int& f()':
main.cpp:6:13: warning: reference to local variable 'x' returned [-Wreturn-local-addr]
int x=1;
^
bash: line 7: 14826 Segmentation fault (core dumped) ./a.out
What's wrong?

int &f()
{
int x=1;
return x;
// x reside on the function calling stack and it is temporary
// when you return the reference to x, after the function has returned,
// x is not there anymore(local variable)
}
if you really want to return a reference to a variable declared inside a function, consider allocate it on the heap, or declare it as a static variable
int &f()
{
int* x= new int;
*x = 1;
return *x;
}
int main(){
int& a = f();
cout << a; // 1
delete &a;
// and MAKE SURE you delete it when you don't need it
}

Related

what is the difference between outside the main function and inside?

So I have seen a program from elsewhere and the declaration is outside from the main function.
Just like this code:
#include<iostream>
using namespace std;
int num1, num2;
int *ptr1 = &num1, *ptr2 = &num2;
char operation, answer;
char *ptrop = &operation;
int main(){
}
But what I am using right now is inside the main function like this:
#include<iostream>
using namespace std;
int main(){
int num1, num2;
int *ptr1 = &num1, *ptr2 = &num2;
char operation, answer;
char *ptrop = &operation;
So what is the difference from it?
In the first case variables and pointers are accessible from all other functions in the file (i.e. it has global scope) whereas in the second case it is only accessible from within main.
I will give you a small example.
Local to main,
#include <iostream>
void fun();
int main(void) {
int x;
fun();
return 0;
}
void fun() {
x = 1; // compiler error: x not declared in this scope
}
Global,
#include <iostream>
void fun();
int x;
int main(void) {
fun();
return 0;
}
void fun() {
x = 1; // compiles as x declared globally
}
All variables declared outside of the main function will have global scope and static storage duration. Variables declared inside main will have automatic storage duration (allocated on the stack) if no storage specifier is provided and will only be visible inside main.

Static declarations and definitions inside of function scope don't change?

Ok, on assigning a static variable declared in a constructor/function (I don't think it matters which) to a compile time defined value, it's as if the variables only been assigned once, see Example:
#include <iostream>
#define y 4
#define z 3
using namespace std;
class Foo
{
public:
Foo(int x)
{
static int i = x;
cout << i << endl;
}
};
int main()
{
Foo p(y);
Foo o(z);
return 0;
}
Expected output:
4
3
Actual output:
4
4
I couldn't find anything on searching, though if this is a dupe just let me know and i'll close the question.
A static local variable is initialized only once when the function it resides in is entered for the first time. So only the first initialization happens, and all further ones are ignored.
Here's your program, modified to illustrate it.
#include <iostream>
#define y 4
#define z 3
using namespace std;
struct Bar {
int i;
Bar(int i) : i{i}
{
cout << "Bar::Bar with " << i << '\n';
}
};
class Foo
{
public:
Foo(int x)
{
static Bar b = x;
cout << b.i << '\n';
}
};
int main()
{
Foo p(y);
Foo o(z);
return 0;
}
If you want each subsequent call to modify i, you need to assign into it:
static int i; // default initialize i.
i = x; // assign a new value into i

Why can't a static data member has the same name with non-static data member?

#include<stdio.h>
#include<vector>
#include<iostream>
using namespace std;
int x = 1;
class foo
{
public:
foo()
{
x = 3;
}
static int x;
void bar() const
{
cout << x << endl;
}
int x;
};
int foo::x = 2;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
here's the compiler output:
test.cc:19:9: error: ‘int foo::x’ conflicts with a previous declaration
int x;
^
test.cc:14:16: note: previous declaration ‘int foo::x’
static int x;
They can't have the same name because which one would you mean when you refer to x in a non-static method?
The language designers could have decided to allow it, e.g. to prefer the non-static one or the reverse. But personally I'm glad they didn't.

undefined reference Static Member C++ [duplicate]

This question already has answers here:
Undefined reference to a static member of the class
(2 answers)
Closed 7 years ago.
I have a code like this. When run, it's return fault: undefined reference to A::x. How can I fix this?
#include <iostream>
using namespace std;
class A
{
private:
static int x;
public:
A(){
}
A(int t) {
x = t;
}
static void f() {
cout<< A::x;
}
int f2() {
return x;
}
};
int main() {
A::f();
A a;
a.f2();
}
You have only declared your static variable, not defined it.
Define it outside of the class using:
int A::x = 0;
You need to add
int A::x = 0; //Or any other value
somewhere outside your class declaration.

Why can't I have a reference to local variable as a non-type template parameter? [duplicate]

This question already has answers here:
Nontype template parameter
(3 answers)
Closed 8 years ago.
I don't understand why this works:
#include <iostream>
template<int& obj>
void foo() { obj = 42; }
int i;
int main()
{
foo<i>();
std::cout << i;
}
and that doesn't:
#include <iostream>
template<int& obj>
void foo() { obj = 42; }
int main()
{
int i;
foo<i>();
std::cout << i;
}
//error: the value of 'i' is not usable in a constant expression
The address of the local variable is a run-time feature, the address of the static variable is a compile time feature.