S
S
sddvxd2018-03-23 15:22:04
C++ / C#
sddvxd, 2018-03-23 15:22:04

How to understand where is the link and where is the copy?

Good afternoon! I would like to ask you what "copy" means.

//func.cpp
//методы класса
const Factory& Factory::compare(const Factory& f)const{
if(f.a_int>this->a)return f; // Возвращаем ссылку на сравниваемый объект
else return *this; //возвращаем ссылку на текущий объект
}

//функции
int _compare(int a, int b){
if(a>b)return a;
else return b;
}

int& __compare(int& a, int& b){
if(a>b)return &a;
else return &b; 
}

Here I described the class method (comparing two fields of objects of the Factory type and returning a reference to the larger one) and 2 functions
I asked the question a little incorrectly, that's what exactly it is: what is a copy, how is it written to a variable. With the managed heap, I understood everything, I still can’t understand how you can return an alias (reference) to a type that is not located on the managed heap and in general why you can create a pointer to it

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
devalone, 2018-03-23
@sddvxd

An area is created on the stack where the value is copied, for example here: The object will be copied during transfer, i.e. memory on the stack will be allocated (the stack pointer will move) and the copy constructor will be called, and then when the function exits, the copy destructor will not occur, because the address will be passed, in general the standard does not guarantee exactly how links are implemented, but usually as pointers. Those. you can think of a reference as a pointer with syntactic sugar.
Why not? If we are talking about a stack, then you can create it, another question is what to specify after exiting the function, it will be garbage

Type& doSomething(Type& obj) {
  Type anotherObj = obj;
  return anotherObj;
}
int main() {
        // .... 
  Type &obj = doSomething(something);
  // здесь при работе c obj будет UB
        // .... 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question