开发者

For no copy classes, can I change the code so that the VS2010 compiler will flag an error on the offending line?

Can I change the code, so that the VS2010 compiler's error message points to the offending line of code?

class NoCopy
{ //<-- error shows up here
   NoCopy( const NoCopy& ); //<-- and error shows up here
   NoCopy& operator=( const NoCopy& );
 public:
   NoCopy(){};
};

struct AnotherClass :NoCopy
{
}; //<-- and error shows up here

int _tmain(int argc, _TCHAR* argv[])
{
  AnotherClass c;
  AnotherClass d = 开发者_开发技巧c; //<-- but the error does not show up here
  return 0;
}

Note that 'NoCopy( const NoCopy& ) = delete;' does not compile in VS2010. I can not use boost.

This was added per Micheal's suggestion:

1>------ Build started: Project: Test, Configuration: Debug Win32 ------
1>  Test.cpp
1>c:\Test\Test.cpp(16): error C2248: 'NoCopy::NoCopy' : cannot access private member declared in class 'NoCopy'
1>          c:\Test\Test.cpp(8) : see declaration of 'NoCopy::NoCopy'
1>          c:\Test\Test.cpp(7) : see declaration of 'NoCopy'
1>          This diagnostic occurred in the compiler generated function 'AnotherClass::AnotherClass(const AnotherClass &)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


The error is not shown at the correct line, because Visual Studio doesn't know where it came from, which is the automatically compiled AnotherClass(const AnotherClass&). You have to explicitly define this in order for Visual Studio to continue finding where the error came from.

class NoCopy {
   NoCopy( const NoCopy& );
   NoCopy& operator=( const NoCopy& );
 public:
   NoCopy(){};
};

struct AnotherClass :NoCopy
{
    AnotherClass();  // Since there is another constructor that _could_ fit,
                     // this also has to be defined
private:
    AnotherClass(const AnotherClass&);  // Define this one
};

int _tmain(int argc, _TCHAR* argv[])
{
  AnotherClass c;
  AnotherClass d = c; //<-- error is now shown here
  return 0;
}

You will now get:

1>\main.cpp(20) : error C2248: 'AnotherClass::AnotherClass' : cannot access private member declared in class 'AnotherClass'

which refers to the "correct" line.


This is the only error I get when trying to compile that:

Error   1   error C2248: 'NoCopy::NoCopy' : cannot access private member declared in class 'NoCopy' main.cpp    11  1

If you make the constructor public, it compiles just fine (though of course it fails to link due to the missing implementations for those member functions).

I could make a guess as to what you really mean: Why is there an access error for the constructor, but not for the = operator? The answer is that the second line is treated as a constructor and not an assignment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜