When to use __declspec(noalias)? - c++

As I understood if (https://learn.microsoft.com/en-us/cpp/cpp/noalias?view=vs-2019) __declspec(noalias) means that the function only modifies memory inside her body or through the parameters, so its not modifying static variables, or memory throught double pointers, is that correct?
static int g = 3;
class Test
{
int x;
Test& __declspec(noalias) operator +(const int b) //is noalias correct?
{
x += b;
return *this;
}
void __declspec(noalias) test2(int& x) { //correct here?
x = 3;
}
void __declspec(noalias) test3(int** x) { //not correct here!?
*x = 5;
}
}

Given something like:
extern int x;
extern int bar(void);
int foo(void)
{
if (x)
bar();
return x;
}
a compiler that knows nothing about bar() would need to generate code that allows for the possibility that it might change the value of x, and would thus have to load the value of x both before and after the function call. While some systems use so-called "link time optimization" to defer code generation of a function until after any function it calls have been analyzed to see what external objects, if any, they might access, MS uses a simpler approach of simply allowing function prototypes to say that they don't access any outside objects which the calling code might want to cache. This is a crude approach, but allows compilers to reap low hanging fruit cheaply and easily.

Related

When does a variable copy be released in lambda function?

As the example below, I define 2 variables x and y. When I call the lambda function twice, it seems like it will not destroy the copy. From 11.14 — Lambda captures | Learn C++ - Learn C++, it says:
Because captured variables are members of the lambda object, their values are persisted across multiple calls to the lambda!
How does C++ manage the memory for lambda function?
int main() {
int x = 1;
static int y = 1;
auto fun = [=]() mutable{
x++;
y++;
cout<<"Inside:\t\t";
cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl;
};
for (int i = 0; i<2; i++) {
fun();
cout<<"Outside:\t";
cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl<<endl;
}
}
Output:
Inside: x:2 y:2
Outside: x:1 y:2
Inside: x:3 y:3
Outside: x:1 y:3
It stores it inside the object itself. Another way to think of your lambda is below. This is "kind of" equivalent to what the compiler is generating, and yes, I'm changing scopes around a bit and I know that, but this may be clearer to a beginner at C++.
static int y = 1; // Moved this out from main
class my_lambda{
public:
my_lambda(int x) : _x(x) {}
~my_lambda() = default;
void operator()()
{
_x++;
y++;
cout<<"Inside:\t\t";
cout<<"_x:"<<_x<<"\t"<<"y:"<<y<<endl;
}
private:
int _x;
};
int main() {
int x = 1;
my_lambda fun{x}; // "Captures" x
for (int i = 0; i<2; i++) {
fun();
cout<<"Outside:\t";
cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl<<endl;
}
}
As you can hopefully see, the "fake lambda" class I made is doing the same thing your actual lambda is. It "captures" x as part of its constructor and copies it to internal storage, which I called _x. And y is just in scope for it, though I moved to global to be above the class declaration.
I'm overloading the () operator to make a class that's callable, which is a normal thing to do in some circumstances. See operator overloading if you wish for more information.
So this is "kind of, sorta" how lambdas work. They take your body and put it into the operator() of the object that's generated, and anything captured is one of the object's variables, with either the actual object (if by value) or a reference, if captured that way.
And to directly answer your question: when fun goes out of scope, it is freed, both in a lambda, and my case.

Trying to understand how to return references to automatic variables [duplicate]

This question already has answers here:
Returning a reference to a local variable in C++
(3 answers)
Closed 8 years ago.
I'm trying to understand why the second piece of code compiles fine, given that the first doesn't.
int & test(void) {
int v = 0;
return v;
}
int main(void){
int & r = test();
return 0;
}
I understand that this doesn't work because you can't pass a reference to an automatic variable that will be deleted. It seems to me that the code below should have the same problem but it doesn't.
int & test1(int & x) {
return x;
}
int & test2(void) {
int x = 0;
return test1(x);
}
int main(void){
int & r = test2();
return 0;
}
Seems like the intermediate function is solving the problem. But why?
Just because something compiles, doesn't mean it works...
The two "alternatives" both suffer from the same exact problem; r, in main, is a dangling reference, what it refers to is long gone, and using it will lead to undefined behavior.
1st snippet
In the first example it's easy enough for the compiler to see that you are returning a reference to a local variable, which (as compilers know) doesn't make any sense.. the referred to instance will be dead when the reference reach main.
The compiler is being a good champ and tells you about the issue.
2nd snippet
In the second example you are doing the same thing, but adding a redirection in-between. A compiler got many tricks up its sleeve, but back-tracing every possible execution path to see if a developer is returning a reference to a local variable, by indirection, isn't one of them.
The compiler can't see that you are being bad, and it cannot warn you about issues it doesn't know about.
Conclusion
Returning a reference to a local variable is bad, no matter how you do it.
Think about what the compiler would have to do to catch the problem you're demonstrating. It would have to look at all callers of test1 to see whether they're passing it a local. Perhaps easy enough, but what if you insert more and more intermediate functions?
int & test1(int & x) {
return x;
}
int & test2(int & x) {
return test1(x);
}
int & test3() {
int x = 0;
return test2(x);
}
int main(void){
int & r = test3();
return r;
}
The compiler would have to look not only at all callers of test1, but then also all callers of test2. It would also have to work through test2 (imagine that it's more complex than the example here) to see whether it's passing any of its own locals to test1. Extrapolate that to a truly complex piece of code--keeping track of that sort of thing would be prohibitively complex. The compiler can only do so much to protect us from ourselves.
The both code examples are ill-formed and have undefined behaviour because local objects will be deleted after exiting the functions. So the references will be invalid.
To understand that the second example does not differ from the first example you could rewrite it the following way (insetad of calling the second function)
/*
int & test1(int & x) {
return x;
}
*/
int & test2(void) {
int x = 0;
/* return test1(x);*/
int &r = x;
return r;
}
As you see there is no any difference between the examples.
To achieve what you want you could the following way
int test()
{
int v = 0;
return v;
}
int main()
{
const int & r = test();
return 0;
}

Assigning pointer to a different address in function

just curious what is the explanation of this?
void f(int * x);
int test = 100;
int main()
{
int z = 35;
int * a = &z;
f(a);
cout<<*a;
..
}
void f(int *x)
{
x = &test;
}
We are taught we can use pointers inside function arguments if we want to modify the "outside" object (as a in this case). But x = &test does not do much, and the cout still prints 35.
I know *x =someVal would work though in f().
In C pointers are passed by value just like ints, floats, etc. So if you want to modify it and have that modification be visible outside of the function call, you need to pass a pointer to the thing you want to modify, in this case that's a pointer to a int pointer:
void f(int **x) {
*x = &test;
}
However, in C++ passing a reference is a much better approach:
void f(int*& x) {
x = &test;
}
If you labeled the question C, what you taught it would be acceptable. For C++ it is techically correct but morally wrong, you should pass by reference to modify the object, not fiddling with pointer and address.
In your code you get what you coded for: pass a pointer and then reassign that poitner's value. That is not visible outside the function. What you intended to do is
void f(int *x)
{
*x = 42;
}
and the C++ version would be like:
void f(int &x)
{
x = 42;
}
int main()
{
int z = 35;
f(z);
cout << z;
}
Due to recommendation of one of the members I am adding my own answer which I derived from the other peoples responses. So thanks go to them.
Basically the problem in my code was that I was changing a copy of my pointer.
The only thing x in function f and the value a passed to f have in common is the address where they point to.

how to load (mov) a class variable into cpu register

I would like to load an int value defined as class member to eax cpu register. smt like this:
class x
{
int a;
x() { a=5; }
do_stuff()
{
__asm
{
mov eax, a; // mov a varbiale content into register
};
}
};
how can I do that with any variable in any class? thanks...
If you are using gcc or icc, this does exactly what you want:
class x
{
int a;
x() { a=5; }
do_stuff()
{
asm("mov %0, %%eax; // mov a varbiale content into register \n"
:
: "r" (a)
: "%eax"
);
}
};
An explanation of rgister constrains and clobber lists is at http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html if you are still interested. On MS VC I would not recommend using inline assembly, because the MS compiler is not good at mixing inline and generated assmbely and produces a lot of overhead.
The best way to load a class variable into a register is by letting the compiler do it for you.
Since the compiler always have to assume the worst, when it comes to reading things from memory, it might be forced to read the value from a class member multiple times, despite the fact that you know that the value has not changed.
For example, in the code below in the function do_stuff, the compiler can not assume that the value of mX is unchanged over the call to foo(). Hence, it is not allowed to place it in a processor register.
int glob;
int glob2;
void foo();
class Test
{
public:
Test(int x) : mX(x) { }
void do_stuff();
private:
int mX;
};
void Test::do_stuff()
{
glob = mX;
foo();
glob2 = mX;
}
On the other hand, in the following case, the source code is written so that tmp can't change over the function call, so the compiler is safe to place it in a register.
void Test::do_stuff()
{
int tmp = mX;
glob = tmp;
foo();
glob2 = tmp;
}
When it comes to inline assembler, I would strongly discourage you from using it. When introducing C++ the situation is even worse, as the underlying representation of a class object is not as straight-forward as that of a C struct (which must be laid out in memory exactly as declared). This mean that a slight change in the class or a migration to a newer compiler could break your code.
You need to get the address of of the instance of class "x" you're working with (mov eax,this), and the offset of "a" relative to the start of "x" (offsetof macro).
It's a lot easier if you just add "a" or "&a" as a parameter of the do_stuff() function.

is it possible in C or C++ to create a function inside another?

Could someone please tell me if this is possible in C or C++?
void fun_a();
//int fun_b();
...
main(){
...
fun_a();
...
int fun_b(){
...
}
...
}
or something similar, as e.g. a class inside a function?
thanks for your replies,
Wow, I'm surprised nobody has said yes! Free functions cannot be nested, but functors and classes in general can.
void fun_a();
//int fun_b();
...
main(){
...
fun_a();
...
struct { int operator()() {
...
} } fun_b;
int q = fun_b();
...
}
You can give the functor a constructor and pass references to local variables to connect it to the local scope. Otherwise, it can access other local types and static variables. Local classes can't be arguments to templates, though.
C++ does not support nested functions, however you can use something like boost::lambda.
C — Yes for gcc as an extension.
C++ — No.
you can't create a function inside another function in C++.
You can however create a local class functor:
int foo()
{
class bar
{
public:
int operator()()
{
return 42;
}
};
bar b;
return b();
}
in C++0x you can create a lambda expression:
int foo()
{
auto bar = []()->int{return 42;};
return bar();
}
No but in C++0x you can http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions which may take another few years to fully support. The standard is not complete at the time of this writing.
-edit-
Yes
If you can use MSVC 2010. I ran the code below with success
void test()
{
[]() { cout << "Hello function\n"; }();
auto fn = [](int x) -> int { cout << "Hello function (" << x << " :))\n"; return x+1; };
auto v = fn(2);
fn(v);
}
output
Hello function
Hello function (2 :))
Hello function (3 :))
(I wrote >> c:\dev\loc\uniqueName.txt in the project working arguments section and copy pasted this result)
The term you're looking for is nested function. Neither standard C nor C++ allow nested functions, but GNU C allows it as an extension. Here is a good wikipedia article on the subject.
Clang/Apple are working on 'blocks', anonymous functions in C! :-D
^ ( void ) { printf("hello world\n"); }
info here and spec here, and ars technica has a bit on it
No, and there's at least one reason why it would complicate matters to allow it. Nested functions are typically expected to have access to the enclosing scope. This makes it so the "stack" can no longer be represented with a stack data structure. Instead a full tree is needed.
Consider the following code that does actually compile in gcc as KennyTM suggests.
#include <stdio.h>
typedef double (*retdouble)();
retdouble wrapper(double a) {
double square() { return a * a; }
return square;
}
int use_stack_frame(double b) {
return (int)b;
}
int main(int argc, char** argv) {
retdouble square = wrapper(3);
printf("expect 9 actual %f\n", square());
printf("expect 3 actual %d\n", use_stack_frame(3));
printf("expect 16 actual %f\n", wrapper(4)());
printf("expect 9 actual %f\n", square());
return 0;
}
I've placed what most people would expect to be printed, but in fact, this gets printed:
expect 9 actual 9.000000
expect 3 actual 3
expect 16 actual 16.000000
expect 9 actual 16.000000
Notice that the last line calls the "square" function, but the "a" value it accesses was modified during the wrapper(4) call. This is because a separate "stack" frame is not created for every invocation of "wrapper".
Note that these kinds of nested functions are actually quite common in other languages that support them like lisp and python (and even recent versions of Matlab). They lead to some very powerful functional programming capabilities, but they preclude the use of a stack for holding local scope frames.
void foo()
{
class local_to_foo
{
public: static void another_foo()
{ printf("whatevs"); }
};
local_to_foo::another_foo();
}
Or lambda's in C++0x.
You can nest a local class within a function, in which case the class will only be accessible to that function. You could then write your nested function as a member of the local class:
#include <iostream>
int f()
{
class G
{
public:
int operator()()
{
return 1;
}
} g;
return g();
}
int main()
{
std::cout << f() << std::endl;
}
Keep in mind, though, that you can't pass a function defined in a local class to an STL algorithm, such as sort().
int f()
{
class G
{
public:
bool operator()(int i, int j)
{
return false;
}
} g;
std::vector<int> v;
std::sort(v.begin(), v.end(), g); // Fails to compile
}
The error that you would get from gcc is "test.cpp:18: error: no matching function for call to `sort(__gnu_cxx::__normal_iterator > >, __gnu_cxx::__normal_iterator > >, f()::G&)'
"
It is not possible to declare a function within a function. You may, however, declare a function within a namespace or within a class in C++.
Not in standard C, but gcc and clang support them as an extension. See the gcc online manual.
Though C and C++ both prohibit nested functions, a few compilers support them anyway (e.g., if memory serves, gcc can, at least with the right flags). A nested functor is a lot more portable though.
No nested functions in C/C++, unfortunately.
As other answers have mentioned, standard C and C++ do not permit you to define nested functions. (Some compilers might allow it as an extension, but I can't say I've seen it used).
You can declare another function inside a function so that it can be called, but the definition of that function must exist outside the current function:
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char* argv[])
{
int foo(int x);
/*
int bar(int x) { // this can't be done
return x;
}
*/
int a = 3;
printf( "%d\n", foo(a));
return 0;
}
int foo( int x)
{
return x+1;
}
A function declaration without an explicit 'linkage specifier' has an extern linkage. So while the declaration of the name foo in function main() is scoped to main(), it will link to the foo() function that is defined later in the file (or in a another file if that's where foo() is defined).