1

I'm learning various details of OOP in C++ and wrote that code. The purpose of that code is to toy with ctor-initializers and learn how to inirialize a reference that is a class attribute.

#include <string>
#include <iostream>

using namespace std;

class Corgi {
    private:
        const string nickname;
        const string& rNickname;
    public:
        Corgi(const string& _nickname): nickname(nickname), rNickname(nickname) {}
};

int main() {
    Corgi buddy("buddy");
    return 0;
}

This code compiles, however, I get this error message when it runs:

Project(1343,0x7fff7b2f2000) malloc: *** mach_vm_map(size=140734714511360) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

I don't understand why I get this error message and how I can fix that. So, why do I get it and how to fix that?

I appreciate any help.

alekscooper
  • 795
  • 1
  • 7
  • 19
  • 1
    nickname(nickname) -> nickname(_nickname). – mfnx Jan 02 '20 at 08:24
  • 2
    During compilation, you should at least get a warning for unused variable nickname. gcc even explicitly says: 'Corgi::nickname' is initialized with itself – mfnx Jan 02 '20 at 08:26
  • @mfnx I use CLion and I can't see any warnings. – alekscooper Jan 02 '20 at 08:37
  • 1
    Concerning this, FYI: [SO: How to enable all compiler warnings in CLion?](https://stackoverflow.com/questions/31790467/how-to-enable-all-compiler-warnings-in-clion). – Scheff's Cat Jan 02 '20 at 08:39

1 Answers1

2
    Corgi(const string& _nickname): nickname(nickname), rNickname(nickname) {}

initializes member nickname with itself which is a problem as member nickname is at this point uninitialized.

A fix:

    Corgi(const string& _nickname): nickname(_nickname), rNickname(nickname) {}

Live Demo on coliru


I considered also this:

    Corgi(const string& nickname): nickname(nickname), rNickname(nickname) {}

which will work for proper initialization of Corgi::nickname (due to the scope rules) but it introduces a new issue for Corgi::rNickname (which is now initialized with a reference to the constructor argument).

For this case, correct would be:

    Corgi(const string& nickname): nickname(nickname), rNickname(this->nickname) {}

Live Demo on coliru

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56