Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question