how can I find where a C++ copy constructor is being USED via a compile error?

北城以北 提交于 2019-12-05 10:47:12

in C++11 you can change the definition to

class Sample {
private:
    // not implemented
    Sample( const Sample& rhs ) = delete;
    Sample& operator=( const Sample& rhs ) = delete;
public:
    // implemented
    Sample();
...
};

prior to C++11 this is usually done by inheritting from a class that declares a private copy constructor such as boost::NonCopyAble (you can simply copy this class, it's only a few lines). In this case your class (or any friends or children) also cannot access the copy constructor and it will generate a compile-time error.

Inherit from a noncopyable class:

class noncopyable
{
private:
    // not implemented
    noncopyable( const noncopyable& rhs );
    noncopyable& operator=( const noncopyable& rhs );
};


class Sample : private noncopyable {
private:
    // not implemented

    Sample( const Sample& rhs );
    Sample& operator=( const Sample& rhs );
public:
    // implemented
    Sample();

    // ...
};

Sample *samp1 = new Sample;
Sample *samp2 = new Sample( *samp1 ); // <<-- compile-time error

This works fine even if you don't have C++11 (where the delete method mentioned elsewhere is probably preferable).

What is error that linker generate? If it is LNK2019 it should be easy to track down function that uses copy constructor:

MSDN says that its format is:

unresolved external symbol 'symbol' referenced in function 'function'

If look this error message, you can find method that calls undefined copy constructor.

Are you trying to get module+line number during compilation? Try making copy-constructor templated:

class A
{
  public:
  template< typename T >
  A( A const & )
  {
  }

  A()
  {
  }
};

int main( void )
{
 A a;
 A b( a ); // main.cpp(43) : error C2558: class 'A' : no copy constructor available or copy constructor is declared 'explicit'

 return ( 0 );
}

If the member is private then you should already get an error at the place of use if it doesn't have permission to access private members.

To get the same error in functions that do have private access you have to put the private copy-ctor declaration somewhere they don't have access to, like as a private member of a base class.

VS2010 doesn't support it yet, but declaring a function as deleted will also work.

As I recall, if you declare it inline, sometimes you'll get a compiler error that says it was declared inline but never defined. That was a while ago, and with gcc. YMMV.

[Shown not to work; leaving this for posterity.]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!