c++/8699: Illegal usage of 'this' in constructor

ppe@astro.unibas.ch ppe@astro.unibas.ch
Mon Nov 25 07:04:00 GMT 2002


>Number:         8699
>Category:       c++
>Synopsis:       Illegal usage of 'this' in constructor
>Confidential:   no
>Severity:       non-critical
>Priority:       medium
>Responsible:    unassigned
>State:          open
>Class:          accepts-illegal
>Submitter-Id:   net
>Arrival-Date:   Mon Nov 25 00:46:02 PST 2002
>Closed-Date:
>Last-Modified:
>Originator:     ppe@astro.unibas.ch
>Release:        gcc-3.2 20020903 (Red Hat Linux 8.0 3.2-7)
>Organization:
>Environment:
Linux 2.4.18 (Red Hat Linux 8.0)
glibc 1.2.93
>Description:
using the 'this' pointer inside outside the curly braces of a constructor is illegal because it is not defined. Gcc compiles it without error but the executable will crash with segmentation fault. See the example code. 

#include <iostream>
#include <cstdlib>

using namespace std;

class Myinterface {
public:
  virtual int callback(int i) = 0;
};

class Tree {
  Myinterface *model;
public:

  Tree(Myinterface *M) { *model=*M; }
  void callem(int i) { 
    cout << "callback callback("<<i<<") returns: ";
    int res=model->callback(i);
    cout << res << endl;}
};


class Model : public Myinterface {
  Tree T;
public:
  int callback(int i) { return i*2;}

  /// ********* The following line is illegal, because
  /// this is not defined outside the curly braces in the
  /// constructur. GCC still compiles it and runtime will
  /// generate segmentation fault when T.callem() is called
  /// in member function runme().
  Model() : T(this) {}
  void runme() {
    cout << "runme\n";
    T.callem(3);
  }
};


int main()
{
  Model x;
  x.runme();
}
>How-To-Repeat:
Compile & run the example code.
>Fix:
Print at least a warning message when compiling the constructor for Model(). E.g.: 'Using undefined 'this' in
constructor Model().' Better print error message. I do not
see how this could be used as a feature.
>Release-Note:
>Audit-Trail:
>Unformatted:



More information about the Gcc-bugs mailing list