Skip to content

Comments

Fix bug on initializing class member reference#355

Open
ericzeng95 wants to merge 1 commit intoLight-City:masterfrom
ericzeng95:fix-bug-1
Open

Fix bug on initializing class member reference#355
ericzeng95 wants to merge 1 commit intoLight-City:masterfrom
ericzeng95:fix-bug-1

Conversation

@ericzeng95
Copy link

#include <iostream>
class Animal {
public:
Animal(int age,std::string name):age_(age),name_(name) {
std::cout << "Animal(int age) is called" << std::endl;
}
private:
int &age_;
const std::string name_;
};
int main() {
Animal animal(10,"hh");
return 0;
}

The original code is wrong. Here class memebr reference variable age_ is binding to constructor parameter age, which is passed by value. When the constructor finishes, this variable goes out of scope, and the binded refernce age_ is dangling. All subsequent usage of age_ is undefined behaviour

@FlyDragonMan
Copy link

FlyDragonMan commented Jun 17, 2025 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants